在django原始查询中使用日期时出错

时间:2011-06-06 05:58:57

标签: django date between

我总是收到此错误TypeError: not all arguments converted during string formatting

这是我的查询

State.objects.raw('...review_create_date between %s and %s group by error_type',[fromdate,todate])

此处fromdate=2011-05-21todate='2011-05-27'

上述查询在mysql提示符下执行,但无法在python shell中运行

请有人帮助我

这是追溯

 Traceback (most recent call last):
 File "<console>", line 1, in <module>
 File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1412, in __iter__
 query = iter(self.query)
 File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 73,  in __iter__
 self._execute_query()
 File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 87, in _execute_query
 self.cursor.execute(self.sql, self.params)
 File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 18, in execute
 sql = self.db.ops.last_executed_query(self.cursor, sql, params)
 File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 216, in last_executed_query
return smart_unicode(sql) % u_params
TypeError: not all arguments converted during string formatting

2 个答案:

答案 0 :(得分:0)

视图中的django原始sql查询

  

我也遇到了这个问题,所以我将旧格式更改为新格式,   格式。我对我有用。

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.py

def location_damageReports(request):
    #static date for testing
    date_from = '2019-11-01'
    date_to = '2019-21-01'
    vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
    damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
    data={"data": damage_report.data}
    return HttpResponse(json.dumps(data), content_type="application/json")

答案 1 :(得分:-1)

尝试使用?代替%s