简体   繁体   中英

Django - manager on ManyToMany relationship

I have 3 models

class Person(models.Model):
  name = models.CharField(max_length=128)

class Company(models.Model):
  name = models.CharField(max_length=128)
  members = models.ManyToManyField (Person, through = 'Membership', related_name = 'companies')

class Membership(models.Model):
  person = models.ForeignKey(Person, on_delete=models.CASCADE)
  company = models.ForeignKey(Company, on_delete=models.CASCADE)
  is_admin = models.BooleanField()

I can then call person.companies.all() to get the list of companies associated with person.

How do I create a manager to have the list of companies associated with person, but whose person is admin (is_admin = True)?

You can filter with:

person.companies.filter(membership__is_admin=True)

This will filter the junction table Membership , such that it will only retrieve Company s for which the Membership has is_admin set to True .

Another option is to retrieve this with:

Company.objects.filter(membership__is_admin=True, members=person)

You can attach this to the Person model with:

class Person(models.Model):
    name = models.CharField(max_length=128)

    @property
    def admin_companies(self):
        return self.companies.filter(membership__is_admin=True)

You can create a manager like the following:

managers.py :

from django.db import models

class AdminCompaniesManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().companies.filter(membership__is_admin=True)

and then in your Person model:

class Person(models.Model):
    name = models.CharField(max_length=128)
    objects = models.Manager()
    administrated_companies = AdminCompaniesManager()

Please mind the objects manager.

Now you can easily call the following in your views:

my_person.administrated_companies.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM