外键计数djang的线性和

2024-09-09 13:13:17 发布

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

我的模型中有一个profile类,如下所示:

class UserProfile(models.Model):
    first_name = ....
    ....

我还有两个类具有配置模型的外键:

class A(models.Model):
    profile = models.ForeignKey(UserProfile)
    ....

class B(models.Model):
    profile = models.ForeignKey(UserProfile)

现在我要过滤活动用户。我想要像这样的东西。但我不知道在django怎么做

UserProfile.objects.filter((2*count(A) + count(B))__gte=10).all()

Tags: django用户name模型modelobjectsmodelscount
1条回答
网友
1楼 · 发布于 2024-09-09 13:13:17

您需要首先在queryset上使用annotate来运行计算,然后才能按它进行筛选

from django.db.models import Count

UserProfile.objects.annotate(
    score=2*Count('a') + Count('b')
).filter(score__gte=10)

相关问题 更多 >