[Answered ]-How to query across generic relations in Django

2👍

def list(self, request):
    items = {}
    for f in request.user.follower_set.all():
        items.setdefault(f.content_type_id, []).append(f.object_id)
    activities = Activity.objects.get_empty_queryset() # get_empty_query_set in <1.5
    for k, v in items.iteritems():
        activities |= Activity.objects.filter(content_type=k, object_id__in=v)

This boils down to 2 queries. It makes use of the fact that if a Follower and an Activity are related to the same object (team or place), the content_type and object_id are the same. A little python processing, and tada, you have all activities related to the current user in 2 queries.

👤knbk

Leave a comment