views:

123

answers:

2

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 and 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!

A: 

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).

KillianDS
Hmmm, I get a 'function' object has no attribute 'order_by' exception on the following line :l = d.log_set.all.order_by('-date','-time')[0]
gtujan
it should be all().order_by()But except: pass is antipatter, either it should be logged to another facility or it should crash loudly.You risk silent data/system corruption this way.
Almad
A: 

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?

gtujan