Django:使用带有Many To Many字段的filter()

时间:2015-01-13 02:16:59

标签: python django django-queryset

我有一个M2M关系,客户可以取消订阅商店。

以下是我的简化模型:

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)

我想编写一个方法,在参数中接受Cliprofile个对象的查询集,并返回仅仅取消订阅的客户端。这是我的东西,但它显然不起作用。

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.

在Django中执行此操作的语法是什么?我怀疑这很容易,但即使阅读文档,我仍然对查询感到困惑。感谢。

1 个答案:

答案 0 :(得分:1)

QuerySet进行操作的方法的模式是使用模型管理器。

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