计算查询集中常见的 ManyToMany 成员

Count common ManyToMany members in queryset

假设我有这样的模型:

class Bar(models.Model):
    pass # some simple Model goes here

class Foo(models.Model):
    bars = models.ManyToManyField(Bar)

和一些填充了 bars 的变量 main_object = Foo(),我怎样才能创建一个查询集,以便用每个实体和 [=14= 之间的公共 bars 元素的数量对其进行注释]?

示例:

有 3 个 Bar 记录,主键为 1、2 和 3。main_objectbars 中设置了 pk=2 作为成员集。

Foo 有两个记录:main_object 和另一个在 bars 中设置了 pk=1 的记录。在这种情况下,我想要一个值为 0 的注释,因为所述记录没有 Barmain_object.

的公共外键

我可以想象类似于 Foo.objects.filter(bars__in=<some_values_here>) 的东西,但不是简单地检查存在,而是像 from django.db.models.Count 那样实际计算它。

它是否可以通过查询集解决,或者我应该通过循环求助于手动计数?

在实际使用中,这种查询方式在相似度排名中很有用,但对我来说似乎并不平凡。

您可以计算:

from django.db.models import Count, Q

Foo.objects.annotate(
    common_count=Count(
        'bars',
        <strong>filter=Q(bars__foo=main_object)</strong>
    )
)

或者如果您只想检索具有至少一个 Bar 共同点的对象:

Foo.objects.filter(
    <strong>bars__foo=main_object</strong>
)<b>.distinct()</b>