因為小程序需要JSON格式做數據綁定
# 獲取前三條數據
activityList = Activity.objects.all()[:3]
#轉化成JSONT格式,可以因為有時間類型報錯可以,做一下數據轉換。
response = json.dumps(list(activityList.values()), cls=DateEncoder)
response_json = {}
response_json['activityjson'] = response
return JsonResponse(data=response_json, safe=False)
# 時間類型報錯數據轉換
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
else:
return json.JSONEncoder.default(self, obj)
希望對你有所幫助。