Django 在 ManyToMany 计数上过滤模型,并具有特定于每个对象的限制?

dra*_*ion 4 django django-models django-queryset

Django 根据 ManyToMany 计数过滤模型?

我的问题与上面的问题非常相似,但有一个区别:模型内部的多对多关系是有限的。

所以而不是

class Party(models.Model):
    organiser = models.ForeignKey()
    participants = models.ManyToManyField('auth.User', 
        related_name="participants")
Run Code Online (Sandbox Code Playgroud)

这将是

class Party(models.Model):
    organiser = models.ForeignKey()
    max_participants = models.PositiveIntegerField()
    participants = models.ManyToManyField('auth.User', 
        related_name="participants")
Run Code Online (Sandbox Code Playgroud)

所以我想找到参与者数量小于的所有 Party 对象Party.max_participants。我如何使用 Django 的 ORM 进行查询?

Wil*_*sem 5

首先,我们Party用参与者数量注释每个对象,然后我们执行一个.filter(..)wheremax_participants大于 ( __gt) then 参与者数量:

from django.db.models import Count, F

Party.objects.annotate(
    num_participants=Count('participants')
).filter(
    max_participants__gt=F('num_participants')
)
Run Code Online (Sandbox Code Playgroud)

因此,这里使用F(..)- 表达式来引用num_participants我们定义的注释,并且作为约束,我们添加该max_participants列大于该数字。