Django的模型并不阿贾克斯序列化 [英] Django models are not ajax serializable

查看:103
本文介绍了Django的模型并不阿贾克斯序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用的尝试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

如果我拿出数据['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 呼叫,默认= EN code_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.

当然,你需要写连接code_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 通过传递给默认= 函数的转储或转储的时间。

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.

另外,你可以使用 JSON 串行这是Django的一部分,看到的的文档

Alternatively, you can use the json serializer that's part of Django, see the docs.

这篇关于Django的模型并不阿贾克斯序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆