【问题标题】:Django - query filter on manytomany is existsDjango - manytomany 上的查询过滤器存在
【发布时间】:2019-06-03 21:31:10
【问题描述】:

我有这样一个模型:

class News(models.Model):
    # ...
    channels = models.ManyToManyField(Channel)
    # ...

获取与频道相关的新闻最有效的方法是什么?

【问题讨论】:

  • 到多个频道?还是一个频道?

标签: django django-models django-queryset


【解决方案1】:

对于给定的频道,您可以使用:

News.object.filter(<b>channels=</b><i>my_channel</i>)

对于一个集合(列表,QuerySet,...):

News.object.filter(<b>channels__in=</b><i>my_channel_collection</i>)

对于至少有一个(或更多)通道的News对象,我们可以查询:

News.objects.filter(<b>channels__isnull=False</b>)<b>.distinct()</b>

.exclude(..):

News.objects.<b>exclude(channels=None)</b>

【讨论】:

  • 但我想查找至少有一个 any 频道的新闻
  • @AlexanderFedotov: 所以你的意思是你想排除没有通道的News 对象,对吧?
【解决方案2】:

这比看起来更复杂。我有一个模型 Stepingredients m2m 字段。只有 603 是正确的 :)

>>> Step.objects.count()
735
>>> Step.objects.filter(ingredients=True).count()
159
>>> Step.objects.exclude(ingredients=False).count()
735
>>> Step.objects.exclude(ingredients=None).count()
603
>>> Step.objects.filter(ingredients__isnull=False).distinct().count()
603
>>> Step.objects.filter(ingredients__isnull=False).count()
59310
>>> sum([step.ingredients.exists() for step in Step.objects.all()])
603

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 2016-04-11
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    相关资源
    最近更新 更多