Django:在多对多字段中使用 filter()
Django: using filter() with Many To Many field
我有一个 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
个对象的查询集,以及 returns 个没有退订的客户端。这是我编辑的,但显然不起作用。
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 中执行此操作的语法是什么?我怀疑这很容易,但即使阅读文档,我仍然对查询感到困惑。谢谢
在 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()
我有一个 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
个对象的查询集,以及 returns 个没有退订的客户端。这是我编辑的,但显然不起作用。
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 中执行此操作的语法是什么?我怀疑这很容易,但即使阅读文档,我仍然对查询感到困惑。谢谢
在 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()