How to have two foreign keys to the same model in Django

djangodjango-models

I want to have two foreign keys to the same model:

class Test(models.model):
    example1 = models.ForeignKey(Example)
    example2 = models.ForeignKey(Example)

I get errors like:

Accessor for field 'example1' clashes with related
field 'Example.test_set'. Add a related_name argument
to the definition for 'example1'.

Best Answer

Try using related_name:

class Test(models.model):
    example1 = models.ForeignKey('Example', related_name='example1')
    example2 = models.ForeignKey('Example', related_name='example2')
Related Topic