Reputation: 175
I have a model that has 2 separate ManyToManyField relations back to itself
class Company(models.Model):
parent = models.ManyToManyField("self", through='CompanyParent', through_fields=('company_child', 'company_parent'), related_name='+')
child = models.ManyToManyField("self", through='CompanyParent', through_fields=('company_parent', 'company_child'), related_name='+')
The above works fine on my localhost Django v3.0.2/ SQLite 3.8.7.2
To actually publish it, I have had to use Django v2.1.15/ SQLite 3.7.17, but with the published version it is chucking out the following errors
companies.Company.child: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.
companies.Company.parent: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.
companies.Company: (models.E003) The model has two many-to-many relations through the intermediate model 'companies.CompanyParent'.
What's going on here? Solved the first 2 issues by adding symmetrical=False
to each model, but no idea how to solve the final error?
Upvotes: 1
Views: 571
Reputation: 175
In the event anyone happens across the same issue; the above is the answer but thought I would expand slightly after making the necessary changes to my own project
If you are looking to have numerous many-to-many within the same model and if you are on a version of Django after 2.2a1, then the best method is the one detailed in my question; two different models which you can easily call on views or templates; for example -
> data.manytomany1
> data.manytomany2
However, before 2.2a1 you will have issues. For me, this is because on cPanel, I have to use Django v2.1.15 due to the older SQLite 3.7.17 utilised. This means that you can only have one ManyToManyField (see above) and use a filter to get your 2nd manytomany > you will only be able to do this in the views.py
Hope that makes sense
Upvotes: 1
Reputation: 1117
You can check this answer to set up two many-to-many relations.
An example from the mentioned answer:
class Person(models.Model):
name = models.CharField(max_length=127, blank=False)
to_users = models.ManyToManyField(
'self',
symmetrical=False,
related_name='from_users',
through='Event',
through_fields=('from_user', 'to_user'),
)
class Event(models.Model):
item = models.ForeignKey(Item, related_name='events')
from_user = models.ForeignKey(Person, related_name='events_as_giver')
to_user = models.ForeignKey(Person, related_name='events_as_receiver')
Upvotes: 3