简体   繁体   中英

Django: using filter() with Many To Many field

I have a M2M relationship where clients than can unsubscribe from shops.

Here are my simplified models:

class Shop(models.Model):
    # ...
    unsubs = models.ManyToManyField(CliProfile, through='Unsubscriptions')

class CliProfile(models.Model):
    # ... The M2M is not repeated here to respect DRY

class Unsubscriptions(models.Model):
    shop = models.ForeignKey(Shop)
    client = models.ForeignKey(CliProfile)

I'd like to write a method that takes a queryset of Cliprofile objects in parameter, and returns clients that didn't unsubscribe only. Here is what I dit but it obviously does not work.

class CliProfile(models.Model):
    #...

    @classmethod
    def get_subscribed_clients(cls, shop, base_clients):

        return base_clients.filter(shop_set__in=shop)
        # This is exactly the opposite I want to do here !!
        # I should filter when shop is in base_clients.shop_set.

What is the syntax to do this in Django? I suspect this to be easy but even reading the doc, I'm still confused with queries. Thanks.

The pattern for a method that operates on a QuerySet is to use a model manager.

class CliProfileManager(models.Manager):
   def get_subscribed_clients(self, shop):
       return self.get_queryset().exclude(unsubscriptions__shop=shop)

class CliProfile(...):
     objects = CliProfileManager()


profiles = CliProfile.objects.filter(...)
subscribed = profiles.get_subscribed_clients()

subscribed = profiles.objects.get_subscribed_clients()

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