控制器功能調用發生錯誤。返回一組數據。我需要將這個數組傳遞給模板。如何序列化數組?
views.py:
def new_authors(request):
new_authors = UserProfile.get_new_authors_entries()
# UserProfile.get_new_authors_entries() retrun:
#[
# {
# 'id': 4,
# 'username': 'zzzzzz'
# },
# {
# 'id': 5,
# 'username': 'wwwwww'
# }
#]
return HttpResponse(json.dumps(new_authors), content_type='application/json')
,但我得到了以下錯誤消息:
File "/usr/lib/python3.4/json/encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable") TypeError: [{'id': 4, 'username': 'zzzzzz'}, {'id': 5, 'username': 'wwwwww'}] is not JSON serializable
models.py:
class UserProfile(User):
@classmethod
def get_new_authors_entries(self, cut_begin=0, cut_end=2):
return self.objects.filter(is_active=1, is_superuser=0).values('id', 'username')[cut_begin:cut_end]
我認爲這個問題來自嘗試序列化'datetime'對象。如果是這樣,[這可能有所幫助](http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python) – CoryKramer 2014-10-10 12:52:31
也請看看:https: //docs.djangoproject.com/en/dev/topics/serialization/ – Brandon 2014-10-10 12:53:25
你應該向我們展示get_new_authors_entries的確切功能。我懷疑它返回一個ValuesQuerySet,而不是一個字典。 – 2014-10-10 12:53:55