Django - Using Multiple Foreign Key To The Same Model
I'm trying to use the same foreign key for two fields in the same model and am getting an error. Im trying to have a primary and secondary on call user, but am not sure how to form
Solution 1:
You have to define different related_name
to both the ForeignKeys
columns. For example:
class ManualRotas(models.Model):
primary_user = models.ForeignKey(User, related_name='related_primary_manual_roats', unique=True, verbose_name="Primary OnCall Engineer")
# related names ^ v
secondary_user = models.ForeignKey(User, related_name='related_secondary_manual_roats', verbose_name="Backup OnCall Engineer", unique=True,blank=True,null=True)
# .... Other columns
Please also refer ForeignKey.related_name
document, which says:
The name to use for the relation from the related object back to this one. It’s also the default value for
related_query_name
(the name to use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.
Related posts:
Post a Comment for "Django - Using Multiple Foreign Key To The Same Model"