我在python中使用DateTime值存在一些问题。当我在以下代码中使用session_start时,我得到了datetime类型的对象不是JSON可序列化错误
views.py
dataSourceBar = {}
dataSourceBar['chart'] = {
"caption": "Rainfall",
"subCaption": "Shown per date",
"xAxisName": "Session",
"yAxisName": "Rainfall in MM",
"theme": "candy"
}
dataSourceBar['data'] = []
objects_with_category_id_2 = dashboard_input.objects.filter(category_category_id=2)
for obj in objects_with_category_id_2:
data = {'label': obj.session_start,
'value': obj.input_input_value}
dataSourceBar['data'].append(data)
model.py
class dashboard_input(models.Model):
session_start = models.DateTimeField(max_length=100)
回溯
Internal Server Error: /dashboard/
Traceback (most recent call last):
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\var\www\VSDK\vsdk\dashboard\views.py", line 69, in Chart
return render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render()})
File "C:\var\www\VSDK\vsdk\dashboard\fusioncharts.py", line 52, in render
self.readyJson = json.dumps(self.constructorOptions, ensure_ascii=False)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable
我从数据库视图检索值,该视图由其他表填充,用户在其中填充数据。
有人可以帮我吗?
答案 0 :(得分:0)
在代码中,模型上有一个Datetime字段。当您引用它是日期时间对象时,正如错误所指出的那样,该对象不可序列化。
您可以通过将其显式转换为字符串来解决此问题,如下所示:
for obj in objects_with_category_id_2:
data = {'label': str(obj.session_start),
'value': obj.input_input_value}
dataSourceBar['data'].append(data)
我不知道obj.input_input_value的类型,但是您可能也不一定必须强制转换。先尝试一下,看看是否适合您。
答案 1 :(得分:0)
如错误消息所示,json不能将datetime对象自动转换为字符串或字典。看来您的view函数正在将所有内容转换为json,然后再将其发送到前端或呈现。
您需要做的就是将DateTime对象显式转换为字符串以使您的代码起作用:
for obj in objects_with_category_id_2:
data = {'label': str(obj.session_start),
'value': obj.input_input_value}
dataSourceBar['data'].append(data)
或者使用datetime中的内置函数对其进行格式化。对于ISO格式,请使用.isoformat():
for obj in objects_with_category_id_2:
data = {'label': obj.session_start.isoformat(),
'value': obj.input_input_value}
dataSourceBar['data'].append(data)
如果希望日期具有其他格式,则可以使用datetime.strftime(format)函数,该函数采用包含结果日期字符串格式的字符串。检查日期时间包文档:https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
也许是这样的:
for obj in objects_with_category_id_2:
data = {'label': obj.session_start.strftime("%d.%m.%Y"),
'value': obj.input_input_value}
dataSourceBar['data'].append(data)
祝你好运!