簡體   English   中英

如何在Django中計算與同一個模型的兩個m2m關系上的相關實體的數量

[英]How to count the number of related entities over two m2m relations to the same Model in Django

大致給出以下兩種模型:

class Person(models.Model):

    name = models.CharField()


class Resource(models.Model):

    people_contributing = models.ManyToManyField(
        Person, 
        related_name='resouces_contributing_to'
    )

    people_involved = models.ManyToManyField(
        Person, 
        related_name='resources_involved_in'
    )

對於所有人,我都希望獲得他/她為之貢獻參與其中的資源的數量。

我嘗試了以下方法:

resources = Resource.objects.all()

participations = Person.objects.filter(
    Q(resources_contributing_to__in=resources) |
    Q(resources_involved_in__in=resources)
).values(
    # group results by person
    'pk'
).annotate(
    count=Count('id')
).values_list(
    'pk',
    'name',
    'count'
).order_by('-count')

print(participations)

這給了我這樣的元組列表:

[
    # (id, name, count)
    (1, 'John Doe', 12),
    (2, 'Jane Doe', 5),
    (3, 'Donald Trump', 3),
]

但是,如果一個人同時在參與和參與,則該資源將被計數兩次,因為該資源將兩次被連接到person表。 我想要的是,如果資源在兩種關系中都存在,則該資源僅被計數一次。

如何更改我的查詢集以防止這種情況?

我正在使用postgresql和Django 1.11。

可以通過對第一個關系中的條目進行計數+對第二個關系中的條目進行計數-對兩個關系中的條目進行計數來實現對出現在任一關系中的條目進行計數。 可以通過以下查詢集在Django中實現:

participations = Person.objects.filter(
    Q(resources_contributing_to__in=resources) |
    Q(resources_involved_in__in=resources)
).annotate(
    count=Count('resouces_contributing_to__id', distinct=True) + Count('resources_involved_in__id', distinct=True) - Count(Case(When(resources_involved_in__id=F('resouces_contributing_to__id'), then='resources_involved_in__id')), distinct=True),
).values_list(
    'pk',
    'name',
    'count'
).order_by('-count')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM