python - Django: Choose from related set in db query
问题描述
I have two models Product
and ProductFilter
.
The ProductFilter
has priority = IntegerField(...)
field and active = BooleanField(...)
.
class ProductFilter(..):
products = ManyToManyField('Product....)
I want to filter products with the active = True
field for their ProductFilter
with the highest priority.
I can choose product_filter
with the highest priority:
product.filters.all().order_by('priority').last()
But this needs a for loop which multiplies number of queries
.
Is it possible to do that in one Query
? Maybe somehow aggregate/annotate
the product_filter
with the highest priority as active_filter
and then
Product.objects.annotate(active_filter=Somehow annotate).filter(active_filter__active=True)
解决方案
推荐阅读
- r - 为什么 SPARQL 查询在 R 包中比在 Land Registry 中的查询时间长 30 倍?
- count - 将 setInterval 计数重置为零
- python - 模拟鼠标按下窗口(有效,但位置不起作用)
- vue.js - 从父级到子级的动态道具绑定
- google-drive-api - NSSM - 试图访问 Software/Google/DriveFS/Share
- javascript - 如何不呈现 ViewChild 元素,而是在父组件中访问它?
- linux - 如何使用自定义 bash 文件(不是来自 .bachrc 或配置文件或其他 shell)初始化/设置 shell?
- babeljs - 删除 @babel/plugin-proposal-class-properties 时出现错误“当前未启用对实验语法 'classProperties' 的支持”
- docker - 绑定卷上的 Chmod 777 无法在 docker 文件中使用
- flutter - 如何覆盖单个小部件的主题?