python - Django intersect count annotate 用于排序
问题描述
在这个问题中,我们得到了一个解决方案,可以根据两个多对多字段的交集对查询进行排序。虽然这是一个很好的答案,但限制是您必须先过滤。
假设我有相同的两个模型。有没有办法通过交叉点数来注释所有结果,这样我就可以显示所有问题,而不管位置如何,但仍然按位置排序?
class Location(models.Model):
name = models.CharField(max_length=100)
class Profile(models.Model):
locations_of_interest = models.ManyToManyField(Location)
class Question(models.Model):
locations = models.ManyToManyField(Location)
我希望我能做这样的事情:
from django.db.models import Count
matching_profiles = Profile.objects.all().annotate(
locnom=Count('locations_of_interest__in=question.locations.all()')
)
有任何想法吗?我只需要进行两个查询并将它们合并吗?
解决方案
我们也可以在Count
函数中移动过滤:
Profile.objects.annotate(
locnom=Count('id', filter=Q(locations_of_interest__in=question.locations.all()))
)
在没有相关s 的s的意义上,这两者是不等价的,或者在没有位置的情况下仍将包括在内,在这种情况下,那将是。Profile
Location
question
.locnom
Profile
0
查询大致如下:
SELECT profile.*,
COUNT(CASE WHEN proloc.location_id IN (1, 4, 5) THEN profile.id ELSE NULL)
AS locnom
FROM profile
LEFT OUTER JOIN profile_locations_of_interest AS proloc
ON profile.id = proloc.profile_id
GROUP BY profile.id
的相关s 的[1, 4, 5]
样本在 哪里?id
Location
question
推荐阅读
- python - Pycharm win32api 模块安装报错:非零退出码(一)
- c# - 如何使用服务器端 Blazor 启用 Windows 身份验证
- c# - 使用 ModelState.IsValid == false 和 AllowHtml 属性发布后返回视图
- docker - Docker - 可以将 NFS 共享挂载到容器中,但不能挂载到容器的子目录中
- bash - 您如何为 aws cloudformation deploy --parameter-overrides 和/或 --tags 添加空间?
- php - laravel 获取帖子列表,包括他们的标签和评论
- sql - Oracle 18c - PL/SQL 限制写入文件的记录
- python-3.x - tkinter 照片图像错误:pyimage1 不存在
- maven - Gitlab跨项目神器
- teradata - Teradata 中止会话,使 DBA 晚上睡得更好