How can I have two foreign keys to the same model in Django?

DjangoDjango Models

Django Problem Overview


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'.

Django Solutions


Solution 1 - Django

Try using related_name:

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

Solution 2 - Django

Django uses some python magic to define relationships between models, some of which involves using the name of the models in the relationships (that's where the 'test' in 'test__set' is coming from.) What's happening, I would guess, is that it's trying to put "test__set" in the Example model twice, once for each foreign key you've got defined.

The error message suggests something to try: define a related_name argument (overriding one of those 'test_set's) that it can use instead of auto-generating two clashing names.

More info here: page has been removed

Current page relating to model relationships: https://docs.djangoproject.com/en/2.0/ref/models/fields/#module-django.db.models.fields.related

Solution 3 - Django

Just do what the error message tells you to do, and if you're unsure what that means, consult the documentation for related_name.

Solution 4 - Django

In django 2.0 Try this:

user = models.ForeignKey(User, on_delete=models.PROTECT, null=True,  related_name='user')
paper = models.ForeignKey(paperRecord, on_delete=models.PROTECT, null=True,  related_name='paper')


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeNView Question on Stackoverflow
Solution 1 - DjangostragerView Answer on Stackoverflow
Solution 2 - DjangoMattView Answer on Stackoverflow
Solution 3 - DjangoJames BennettView Answer on Stackoverflow
Solution 4 - Djangopranjal0819View Answer on Stackoverflow