Django 模型不是 ajax 可序列化的 [英] Django models are not ajax serializable
问题描述
我有一个简单的视图,我用它来试验 AJAX.
I have a simple view that I'm using to experiment with AJAX.
def get_shifts_for_day(request,year,month,day):
data= dict()
data['d'] =year
data['e'] = month
data['x'] = User.objects.all()[2]
return HttpResponse(simplejson.dumps(data), mimetype='application/javascript')
这将返回以下内容:
TypeError at /sched/shifts/2009/11/9/
<User: someguy> is not JSON serializable
如果我取出 data['x'] 行,这样我就不会引用任何模型,它会起作用并返回:
If I take out the data['x'] line so that I'm not referencing any models it works and returns this:
{"e": "11", "d": "2009"}
为什么 simplejson 不能解析我的默认 django 模型之一?我使用的任何模型都会得到相同的行为.
Why can't simplejson parse my one of the default django models? I get the same behavior with any model I use.
推荐答案
你只需要在你的 .dumps
调用中添加一个 default=encode_myway
参数来让simplejson
知道当你向它传递它不知道的类型的数据时该怎么做——你为什么"问题的答案当然是你没有告诉穷simplejson
如何处理您的模型实例之一.
You just need to add, in your .dumps
call, a default=encode_myway
argument to let simplejson
know what to do when you pass it data whose types it does not know -- the answer to your "why" question is of course that you haven't told poor simplejson
what to DO with one of your models' instances.
当然你需要编写 encode_myway
来提供 JSON 可编码的数据,例如:
And of course you need to write encode_myway
to provide JSON-encodable data, e.g.:
def encode_myway(obj):
if isinstance(obj, User):
return [obj.username,
obj.firstname,
obj.lastname,
obj.email]
# and/or whatever else
elif isinstance(obj, OtherModel):
return [] # whatever
elif ...
else:
raise TypeError(repr(obj) + " is not JSON serializable")
基本上,JSON 知道非常基本的数据类型(字符串、整数和浮点数,分组为字典和列表)——作为应用程序员,您有责任将其他所有内容与这些基本数据类型进行匹配,并在 simplejson
通常通过在 dump
或 dumps
时间传递给 default=
的函数完成.
Basically, JSON knows about VERY elementary data types (strings, ints and floats, grouped into dicts and lists) -- it's YOUR responsibility as an application programmer to match everything else into/from such elementary data types, and in simplejson
that's typically done through a function passed to default=
at dump
or dumps
time.
或者,您可以使用 Django 中的 json
序列化程序,请参阅 文档.
Alternatively, you can use the json
serializer that's part of Django, see the docs.
这篇关于Django 模型不是 ajax 可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!