django注释计数过滤器
我正在尝试计算某些模型的每日记录,但我希望仅对某些 fk 字段 = xy 的记录进行计数,因此我得到了创建新记录但有些可能返回 0 的天数列表
class SomeModel(models.Model):
place = models.ForeignKey(Place)
note = models.TextField()
time_added = models.DateTimeField()
。名称为“NewYork”的地点
data = SomeModel.objects.extra({'created': "date(time_added)"}).values('created').annotate(placed_in_ny_count=Count('id'))
这有效,但显示所有记录..所有地点。
尝试过过滤,但它不会返回没有 place.name="NewYork"
记录的天数。那不是我需要的。
I am trying to count daily records for some model, but I would like the count was made only for records with some fk field = xy so I get list with days where there was a new record created but some may return 0.
class SomeModel(models.Model):
place = models.ForeignKey(Place)
note = models.TextField()
time_added = models.DateTimeField()
Say There's a Place with name="NewYork"
data = SomeModel.objects.extra({'created': "date(time_added)"}).values('created').annotate(placed_in_ny_count=Count('id'))
This works, but shows all records.. all places.
Tried with filtering, but it does not return days, where there was no record with place.name="NewYork"
. That's not what I need.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您似乎想知道,对于添加任何对象的每一天,当天创建的对象中有多少个地点的名称为纽约。 (如果我误解了,请告诉我。)在需要外连接<的SQL中/a>:
因此您始终可以使用 原始 SQL 查询:
注释:
我还没有尝试弄清楚这是否可以用 Django 的查询语言表达;可能是,但是 正如开发人员所说,数据库 API 是“一条捷径,但不一定是万能的。”)
m.id
是SQL查询中多余的,但是 Django 要求“主键...必须始终包含在原始查询中”。您可能不想将文字
'New York'
写入查询中,因此 传递参数:raw('SELECT ... AND p.name = %s ...', [地名])
。It looks as though you want to know, for each day on which any object was added, how many of the objects created on that day have a place whose name is New York. (Let me know if I've misunderstood.) In SQL that needs an outer join:
So you can always express this in Django using a raw SQL query:
Notes:
I haven't tried to work out if this is expressible in Django's query language; it may be, but as the developers say, the database API is "a shortcut but not necessarily an end-all-be-all.")
The
m.id
is superfluous in the SQL query, but Django requires that "the primary key ... must always be included in a raw query".You probably don't want to write the literal
'New York'
into your query, so pass a parameter instead:raw('SELECT ... AND p.name = %s ...', [placename])
.