David Dahan
David Dahan

Reputation: 11162

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.

Upvotes: 0

Views: 84

Answers (1)

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

Upvotes: 1

Related Questions