[Fixed]-Django manytomany with extra field – in some cases

1👍

For your use case, it should be OK to keep invited_reason with null to keep your models simple.

For very complex realtionships, keep in mind that many-to-many relationships can be created manually without a “ManyToManyField”, even without a ‘through’ field, holding many types of relationships between entities:

class Person(models.Model):
    pass


class Group(models.Model):
    pass


class Membership(models.Model):  # "PersonGroup"
    person = models.ForeignKey(Person, related_name='memberships')
    group = models.ForeignKey(Group, related_name='memberships')

    # other fields...

    class Meta:
        unique_together = (
            ('person', 'group'),  # optional
        )


class Invitation(models.Model):  # "InvitedPersonGroup"
    person = models.ForeignKey(Person, related_name='invitations')
    group = models.ForeignKey(Group, related_name='invitations')

    # other fields...

    class Meta:
        unique_together = (
            ('person', 'group'),  # optional
        )

This means any relationship can be customized as needed for its purpose.

👤Udi

Leave a comment