django 聚合或注释
我知道这是一件非常愚蠢的事情,但我似乎不了解 Django 聚合和注释函数。
我有一组非常简单的模型:Events
、Areas
和 Types
。事件具有指向 Area
和 Type
的外键。我只想知道任何区域即将发生的事件的数量以及任何类型都相同的数量,即 Area1 - 5 即将发生的事件、Area2 - 6 或 Type1 - 34 个事件 等等。
我想避免编写自定义 SQL 和 q 运算符(如果可能的话)。
This is a very stupid thing, I know, but I just don't seem to get the handle on Django aggregate and annotate functions.
I have a very simple set of models: Events
, Areas
and Types
. An event has foreign keys pointing to Area
and Type
. I would simply like to have the number of forthcoming events for any area and the same for any type, i.e. Area1 - 5 forthcoming events, Area2 - 6, or Type1 - 34 events and so on.
I would like to avoid writing custom SQL, and the q operator if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于给定区域:
注释
或
请参阅以下文档:
https:// docs.djangoproject.com/en/dev/ref/models/querysets/#annotate
for a given area:
annotation
or
See the following docs:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate
如果您只需要单个区域的事件总数,则不需要
annotate
或aggregate
,一个简单的count
就可以了:如果您想要多个区域的事件计数,则需要将
annotate
与values
结合使用:If you just need the total number of events for a single area, you don't need either
annotate
oraggregate
, a simplecount
will do:If you want the count of events for multiple areas, you need
annotate
in conjunction withvalues
:非常感谢大家。我遇到的问题记录在上一个版本中,它与注释和过滤器优先级有关。
我的错误在于我首先进行注释,然后进行过滤。
Thank you all very much. The problem I was having is documented in the last version, it is about the annotate and filter precedence.
My error was in the fact that I was doing annotate first and filter second.
给定模型事件和区域为:
为了获得每个区域中的事件总数,您可以执行以下操作:
Given the models Event and Area as:
In order to get the total number of events in each area, you can do: