Django:对多对多字段使用filter()

2024-09-29 23:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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的语法是什么?我怀疑这很容易,但即使阅读了医生,我仍然困惑于疑问。谢谢。你知道吗


Tags: tobasemodelhereismodelsfiltershop
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:18

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

相关问题 更多 >

    热门问题