Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django GenericForeignKey using related_name

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?

like image 234
benwad Avatar asked Oct 20 '22 22:10

benwad


1 Answers

You could have a look at Reverse generic relations

like image 96
CJ4 Avatar answered Oct 27 '22 08:10

CJ4