Example: If I have Event and Like model, and the second one has generic relation to the first one (i.e. it has content_type, object_id and content_object fields), then if I want to get all events which current user liked, I would just make this call in a view: generic_rel_filter(Event, 'like', 'person', self.request.user.pk)

Note that this function isn't intended to be used with user specified parameters, otherwise it's prone to SQL injection attacks.

P.S. It can be done with ORM but then it would go with three queries, which is much slower than the method above (which uses only one query to do the same): Event.objects.filter(pk__in=Like.objects.filter(content_type=ContentType.objects.get(model='event'), person=self.request.user).values_list('object_id', flat=True))

Change History (9)

Thanks for the suggestion; the code, as given, is not fit for general use because it makes assumptions which are not guaranteed to hold:

it assumes the model and target belong to the same app

it assumes the modles use the default table names (i.e. none of the models specifies Meta.db_table)

it assumes the default app label (a different one can be set via AppConfig objects)

it assumes the names content_type_id and object_id for the components of the generic FK -- these are not even defaults, but only a convention

Further, the code uses target in a way which bakes some of these assumptions into the API, not just the implementation.

I suggest you bring the idea up on the DevelopersMailingList, to get a wider discussion of whether the feature fits for inclusion in Django, and if so, to define an API everyone agrees on. When you do, please make sure you present the problem before you suggest your solution.