ordering by generic foreign key

69 views
Skip to first unread message

Bastian

unread,
Oct 18, 2012, 12:46:13 PM10/18/12
to django...@googlegroups.com
Hi, I'm not sure to understand what I'm doing here :) I have a model of a photo with name, description, image field... and a generic foreign key called 'likes' to store the photo in users' favorites:
likes = generic.GenericRelation(Like)

and in the Like model I have:
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()

Now when I want to display a user's favorites I can do:
q = Q(likes__user=user)
favorites = Photo.objects.filter(q)

it works ok but the result is ordered by Photo pk so if a user likes a photo that has been uploaded a long time ago it appears very far away in the favorites list. I would like to order that list by the pk of the Like object but I have no idea how to do that.
I don't know if I made myself clear. Any help is welcome.
Cheers,
Bastian

Bastian

unread,
Oct 19, 2012, 6:11:47 AM10/19/12
to django...@googlegroups.com
I tried that:

favorites = Photo.objects.filter(likes__user=user).order_by("-likes__id")

and it seems to work well in all the tests. The only thing I don't understand is how it works. Because in this generic relation there are various 'likes' for each 'Photo' object and so the 'filter(likes__user=user)' part must iterate through them in a way. Anyway it works.
Cheers,
Bastian
Reply all
Reply to author
Forward
0 new messages