2014-10-10 67 views
2

控制器功能调用发生错误。返回一组数据。我需要将这个数组传递给模板。如何序列化数组?

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] 
+0

我认为这个问题来自尝试序列化'datetime'对象。如果是这样,[这可能有所帮助](http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python) – CoryKramer 2014-10-10 12:52:31

+0

也请看看:https: //docs.djangoproject.com/en/dev/topics/serialization/ – Brandon 2014-10-10 12:53:25

+2

你应该向我们展示get_new_authors_entries的确切功能。我怀疑它返回一个ValuesQuerySet,而不是一个字典。 – 2014-10-10 12:53:55

回答

1

由于这post建议,您可以使用默认参数json.dumps来处理您的问题:

>>> dthandler = lambda obj: (
...  obj.isoformat() 
...  if isinstance(obj, datetime.datetime) 
...  or isinstance(obj, datetime.date) 
...  else None) 
>>> json.dumps(datetime.datetime.now(), default=dthandler) 
'"2010-04-20T20:08:21.634121"' 

我有同样的问题,序列化对象datetime,这帮助。

和平

+0

我试图排除数据集类型datetime的字段。问题仍然存在 – dert 2014-10-10 13:35:51

+0

你能告诉我们你准确做出了哪些修改吗? – Oscar 2014-10-10 15:02:44

+0

我在我的答案中添加了代码,只是认为用别人的答案来评价并不好。 – Oscar 2014-10-10 15:20:11