Sunday, January 16, 2011

GROUP BY fields appearance, bug or feature?

Hi!

Suppose following model:

class UserEmail(models.Model):
"""User email"""

user = models.ForeignKey(User, db_index=True,
null=True, blank=True, editable=False)
"""User recieving the email"""

added = models.DateTimeField(_("added"), auto_now_add=True)
"""Added to database"""

subject = models.CharField(_('subject'), max_length=128)
"""Subject"""

message = models.TextField(_('message'))
"""Message"""

How can I retrieve list of users and their latest email subject?

This almost works:

User.objects.all()\
.annotate(latest_email_added=Max('useremail__added'))

But it does not give me the other fields of latest email such as
subject, so I try to add other fields using extra:
User.objects.all()\
.annotate(latest_email_added=Max('useremail__added'))\
.extra(select={'email_subject' : 'myapp_useremail.subject'})

Suddenly it adds a GROUP BY to the query with a long list of fields
that should not be there, which breaks everything, now I get multiple
rows per user which is not wanted.

If I try to modify the group_by manually, like this:
a = User.objects.all()\
.annotate(latest_email_added=Max('useremail__added'))\
.extra(select={'email_subject' : 'dmusic_useremail.subject'});
a.query.group_by = [('auth_user', 'id')];
print a.query

There is still one extra field in group by making it break:
... GROUP BY "auth_user"."id", (dmusic_useremail.subject)

Can someone elaborate this behavior?

Any help is appreciated, thanks!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate