在SQLite中注释 [英] Annotate in SQLite

查看:914
本文介绍了在SQLite中注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

class Model(...):
  date = DateField()
  user = ForeignKey()
  data = ForeignKey()
  time = IntegerField()

我想为每个用户提供单个数据的时间字段,所以我做:

I'd like to make sum of time field for every user for a single data, so I do:

Model.objects.filter(date=..., data=...).values('user_id').annotate(time=Sum('time'))

但我收到的结果如下:

[{'user_id':1,时间':20},{'user_id':1,'time':10},{'user_id':2,'time':20}]

[{'user_id': 1, 'time': 20},{'user_id': 1, 'time': 10}, {'user_id': 2, 'time': 20}]

分组不起作用。我检查了由django生成的查询,我不知道为什么django使用日期和数据进行分组,不仅仅是用户。我做错了,这只是SQLite问题?

So the grouping does not work. I checked query generated by django and I don't know why django uses date and data for grouping as well, not only user. Am I doing something wrong or this is only SQLite issue?

推荐答案

你应该附加。 order_by()到您的查询集,以清除默认模式订购。

You should append .order_by() to your query set to clear default model ordering.

对于您的代码:

(Model.objects.filter(date=…, data=…)
              .values('user_id')
              .annotate(time=Sum('time'))
              .order_by())                        # <---- Here

这是在默认订购文档警告


除了它不会很好的工作。按名称将
也在分组中发挥作用...您应该...清除查询中的任何顺序。

"Except that it won't quite work. The default ordering by name will also play a part in the grouping ... you should ... clearing any ordering in the query."

这篇关于在SQLite中注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆