过滤注释而不删除结果
考虑使用注释的模型和查询,例如 Django 文档中的以下示例: http://docs.djangoproject.com/en/dev/topics/db/ aggregation/
Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
该查询的结果将仅包含与过滤器匹配的对象(即 book_ rating 大于 3.0),并且这些对象已被注释。但是,如果我希望查询包含所有对象,但仅注释与过滤器匹配的对象(或者例如用 0 注释它们),该怎么办?或者这有可能吗?
Consider a model and a query using annotations, for example the following example from the Django documentation:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/
Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
The result of this query will only contain objects matching the filter (i.e. has a book_rating greater than 3.0), and these objects has been annotated. But what if I want the query to contain all objects, but only annotate objects which matches a filter (or for example annotate them with 0)? Or is this even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您不能这样做 - 因为底层 SQL 不是这样工作的。
我唯一能想到的是做两个查询,一个带有过滤器/注释,一个没有,然后在 Python 中迭代它们,将注释附加到非过滤列表中的匹配对象。
No, you can't do that - because that's not how the underlying SQL works.
The only thing I can think of is to do two queries, one with the filter/annotation and one without, then iterate through them in Python, appending the annotation to the matching objects from the non-filtered list.