Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 724
MikeN Avatar asked Feb 12 '09 21:02

MikeN


People also ask

Can a Django model have 2 foreign keys?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.

Can a class have 2 foreign keys?

Foreign Key ColumnsA single column can have multiple foreign key constraints. For an example, see Add multiple foreign key constraints to a single column.

Can an object have multiple foreign keys?

Yes, that makes perfect sense. It is not at all uncommon to have a table with multiple foreign keys to other tables.


2 Answers

Try using related_name:

class Test(models.model):     example1 = models.ForeignKey('Example', related_name='example1')     example2 = models.ForeignKey('Example', related_name='example2') 
like image 145
strager Avatar answered Sep 21 '22 08:09

strager


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

like image 20
Matt Avatar answered Sep 22 '22 08:09

Matt