Django GenericForeignKey using related_name

database, django, foreign-keys, python

Solution

You could have a look at Reverse generic relations

Problem

I'm trying to refactor my schema so that a field that is currently a simple `ForeignKey` becomes a `GenericForeignKey`. So, in my model, this: ``` ref_track = models.ForeignKey(Track, unique=False, related_name='posts_by_ref') ``` ...becomes this: ``` ref_content_type = models.ForeignKey(ContentType) ref_id = models.PositiveIntegerField() ref_object = generic.GenericForeignKey('ref_content_type', 'ref_id') ``` Previously I was using `posts_by_ref` in a number of database queries, for example checking the submission status of the posts attached to a track (the post object is where the above fields are). However, I understand that `related_name` is not supported when using a `GenericForeignKey`, so is there another way to replicate this behaviour?

Original source