开发者

Django query get recent record for each entry and display as combined list

I have two models device and log setup as such:

class device(models.Model):
   name = models.CharField(max_length=20)   
   code = models.CharField(max_length=10)
   description = models.TextField()

class log(model.Model):
   device = models.ForeignKey(device)
   date = models.DateField()
   time = models.TimeField()
   data = models.CharField(max_length=50)

how do I get a list which contains only the most recent record/log (based on time and date) for each device an开发者_开发技巧d combine them in the format below:

name,code,date,time,data

being a Django newbie I would like to implement this using Django's ORM. TIA!

EDIT:

still not working for me, although i tried this approach:

devices=device.objects.annotate(latest_log_date=Max('log_date')),latest_log_time=Max('log_time'))

logs=get_list_or_404(log.objects.filter(date__in=[b.latest_log_date for b in devices],time__in=[b.latest_log_time for b in devices]))`

it only gives me the most recent log from each device...doesn't combine both of course...but based on that how do I present it in name,code,date,time,data format?


Something like this:

for d in device.objects.all():
    try:
        l = d.log_set.all().order_by('-date','-time')[0]
        text = "%s,%s,%s,%s,%s" % (d.name, d.code, l.date, l.time, l.data)
        #do something with text
    except:
        pass

Try/except is for when no log is found for the device. It can be you have to put something like str(d.date) to make the formatting work (or even better, use some strftime or something alike to give it the format you want).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜