Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate raising AttributeError 'object has no attribute'

Hi I'm trying to use django's annotate and I think I'm doing everything ok but I must be missing something because I'm getting an Attribute Error

Here are my models

class Operation(models.Model):
    ...

class Message(models.Model):
    operation = models.ForeignKey(Operation)
    sent_on = models.DateTimeField(auto_now_add=True)
    ...

And here is what I'm trying to do:

    ops = Operation.objects.filter(...)
    ops.annotate(last_message=Max('message__sent_on'))
    ops.order_by('-last_message')

    print ops[0].last_message

And I'm getting

AttributeError at ...
'Operation' object has no attribute 'last_message'

Notice that if I change the annotate to ops.annotate(last_message=Max('whatever')) I get a FieldError, so the previous syntax was right... but why then can't I access the last_message field?

I'm using django 1.6.10

Thanks!

like image 316
Martin Massera Avatar asked Sep 07 '25 08:09

Martin Massera


1 Answers

Queryset methods do not modify the existing queryset in place, they return a new one. So your annotate and ops calls are in fact not actually doing anything, as they create a new queryset and then it is immediately thrown away.

You need to reassign the result of the calls:

ops = Operation.objects.filter(...)
ops = ops.annotate(last_message=Max('message__sent_on'))
ops = ops.order_by('-last_message')

or just do it in one go:

ops = Operation.objects.filter(
    ...
).annotate(
    last_message=Max('message__sent_on')
).order_by('-last_message')
like image 102
Daniel Roseman Avatar answered Sep 10 '25 05:09

Daniel Roseman