使用Django从数据库中选择聚合计算的日期格式 [英] Selecting date formats for aggregate calculations from database with Django

查看:302
本文介绍了使用Django从数据库中选择聚合计算的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用extra()函数来格式化日期,如下所示:

p>

  ... extra(select =strftime('column','%m /%Y')as t ('t')。注释(SUM(foo))

它适用于sqlite3。 / p>

在sqlite3中,我可以使用strftime(),但是不适用于MySQL。
在MySQL中,我可以使用date_format(),但这不适用于sqlite3。



我如何重写这两个数据库类型? / p>

大多数开发人员只需在他们的开发机器上使用sqlite3,而在prod服务器上使用MySQL。



谢谢!

解决方案

在MySQL数据库中运行以下内容,创建转发功能。

 分隔符// 

创建函数strftime(d日期,格式varchar(255))
RETURNS varchar(64)
语言SQL
DETERMINISTIC
COMMENT'date_format'的同义词'
返回date_format(d,格式);
//
分隔符;


I would like to do aggregate calculations based on month for a datetime field.

I am currently using the extra() function to format the date like:

...extra(select="strftime('column', '%m/%Y') as t").values('t').annotate(SUM(foo))

and it works great for sqlite3.

In sqlite3 I can use strftime(), but that doesn't work with MySQL. In MySQL I can use date_format(), but that doesn't work with sqlite3.

How can I rewrite this to work for both database types?

Most of the developers simply use sqlite3 on their dev machines, and MySQL is used on the prod server.

Thanks!

解决方案

Run the following in your MySQL database, to create a forwarding function.

delimiter //

create function strftime ( d date, format varchar(255) )   
   RETURNS varchar(64)
   LANGUAGE SQL
   DETERMINISTIC
   COMMENT 'synonym for date_format'
   return date_format(d, format) ;
//
delimiter ;

这篇关于使用Django从数据库中选择聚合计算的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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