【发布时间】:2014-12-05 15:34:23
【问题描述】:
错误发生在控制器函数调用中。返回一个数据数组。我需要将此数组传递给模板。
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对象。如果是这样,this may help -
您应该向我们展示
get_new_authors_entries的确切作用。我怀疑它返回 ValuesQuerySet,而不是字典。
标签: python json django python-3.x