[Fixed]-Django – using multiple foreign key to the same model

28πŸ‘

βœ…

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:

Leave a comment