Django: model has two ManyToMany relations through intermediate model

前端 未结 1 847
天涯浪人
天涯浪人 2020-12-15 22:37

So I am new to Django, and want to describe the scenario: there are a bunch of Persons, and there are a bunch of Items, and a person passes I

相关标签:
1条回答
  • 2020-12-15 22:54

    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()).

    0 讨论(0)
提交回复
热议问题