8👍
✅
What you’re describing sounds reasonable enough. There may be a technical reason why that’s disallowed; one semantic reason is that each ManyToManyField
implies the creation of a new table, and there can’t be two tables with the same name (i.e. represented by the same class).
One alternative approach (shorter and more DRY) would be this:
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')
The table structure is the same but the descriptors are different. Accessing related people is a bit easier but accessing related items is a bit harder (for example, instead of person.out_items.all()
you would say Item.objects.filter(events__from_user=person).distinct()
).
Source:stackexchange.com