0

我需要编写 django 原始查询来过滤年份和月份。为此,我尝试了以下代码。

cursor = connection.cursor()
cursor.execute('SELECT  SUM(work_time) AS sum FROM structure_tracking_details WHERE employee_id = %s AND tree_id=%s AND project_structure=%s AND year(date)=%s AND month(date)=%s  GROUP BY project_structure ', [employee_id,tree_id,project_structure,select_year,select_month] )
sum1=str(cursor.fetchone())

但它告诉no such function: year我的代码有什么问题?

4

2 回答 2

3

SQLite doesn't have a YEAR() function. If you want year, you can use something like this -

select strftime('%Y', datetime(datefield, 'unixepoch')) as year from table_name

So instead of writing year(date)=%s, you could write strftime('%Y', date) = %s. It should work. I haven't tried it.

Or leave all these headache and use Django's ORM. You should be using that at the first place.

Edit:
According to OP, this query worked -

cursor.execute("SELECT SUM(work_time) AS sum FROM structure_tracking_details WHERE employee_id = %s AND tree_id=%s AND project_structure=%s AND strftime('%%Y', date) = %s AND strftime('%%m', date) = %s GROUP BY project_structure ", employee_id, tree_id, project_structure, select_year, select_month])

The %Y needed to be escaped using %%Y.

于 2013-05-22T10:09:34.503 回答
2

为什么不使用 ORM?

如果你有这样的模型:

class Work(models.Model):
    date_field = models.DateField()
    # your other fields

您可以使用yearmonth查找来执行此查询:

Work.objects.filter(date_field__year=2013,date_field__month=2)

现在,添加您的其余内容,即汇总work_time和分组:

from django.models import Sum

Work.objects.filter(date_field__year=2013,
                    date_field__month=2,
                    employee_id=1,
                    ...).values('project_structure').aggregate(total=Sum('work_time'))
于 2013-05-22T10:08:09.720 回答