Multiple ManyToManyFields with same through table

21 Views Asked by At

I have an Organization model and a custom link table model linking it to User like this:

class Organization(models.Model):
    name = models.CharField(max_length=255)

class OrganizationUser(models.Model):
    organization = models.ForeignKey(
        Organization,
        related_name="organization_users",
        on_delete=models.CASCADE
    )
    user = models.ForeignKey(
        "users.User",
        related_name="organization_users",
        on_delete=models.CASCADE
    )
    link_type = models.CharField(
        choices=LinkTypeChoices.choices,
        max_length=64,
        default=LinkTypeChoices.MEMBER
    )

To make it easier to query through to User from Organization, I want to set up a ManyToManyField with through="app_name.OrganizationUser". However, it would be nice to automatically filter this queryset based on the value of OrganizationUser.link_type.

Is there any reason why I shouldn't or can't set up two ManyToManyFields on Organization pointing to User through OrganizationUser with different limit_choices_to values filtering for different values of OrganizationUser.link_type?

For example, I would like to be able to write Organization.owners.all() and Organization.members.all(), running both through the same link table, and get different results.

0

There are 0 best solutions below