我有一个 Django 应用程序,它使用基于 django 聚合查询集的 Google Visualization API(Google 图表)生成一些图表。 Google Charts API 期望数据采用正确的格式,以便正确生成图表(即日期必须是 JavaScript 类型“日期”,而不是整数或 float )。
假设我想为我的模型帖子创建一个聚合,以显示特定用户每年的记录总数。我的代码看起来像这样:
qset = Post.objects.filter(user__id=1).extra(select={"year": "date_part('year', cdt)"}\
.values("year").annotate(num_records=Count("id")).order_by()
这个工作相当不错,除了 date_part()
postgresql 函数用于从 timestampz 字段中提取年份,返回为 float ,而不是整数,以防弄乱我的图表数据。
从 psql 运行类似的查询会返回一个整数,这正是我所期望的。
select date_part('year', cdt) from public.core_post where id=6543;
date_part
-----------
2011
(1 row)
再次,使用 psycopg2 库运行一个小型 python 程序给了我同样的问题:
import psycopg2
def main():
conn_string = "host='localhost' dbname='mydb' user='username' password='secret'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
sql = "select date_part('year', cdt) from public.core_post where id=6543;"
cursor.execute(sql)
for rec in cursor.fetchone():
print type(rec), rec
if __name__ == '__main__':
main()
<type 'float'> 2011.0
[Finished in 0.1s]
有人知道为什么,或者它是否可以修复吗?
(我当然可以在将数据传递到图形库之前编写一个函数来解决此问题,但我宁愿能够传递查询集(因为这就是我编写图形库的方式)。)
最佳答案
好吧,尴尬了。 只需重新阅读有关 date_part 的 PostgreSQL 文档即可,其中明确指出:
Function Return Type
date_part(text, interval) double precision
我会接受这个答案,并将其留作将来引用。
通过将 date_part()
的结果转换为 int 来解决。
qset = Post.objects.filter(user__id=1).extra(
select={"year": "date_part('year', cdt)::int"}) \
.values("year").annotate(num_records=Count("id")).order_by()
关于python - psycopg2 返回 date_part 函数的错误(?)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13968574/