有很多关于如何序列化模型QuerySet的文档,但是如何将模型实例的字段序列化为JSON呢?


当前回答

要序列化和反序列化,请使用以下命令:

from django.core import serializers

serial = serializers.serialize("json", [obj])
...
# .next() pulls the first object out of the generator
# .object retrieves django object the object from the DeserializedObject
obj = next(serializers.deserialize("json", serial)).object

其他回答

要序列化和反序列化,请使用以下命令:

from django.core import serializers

serial = serializers.serialize("json", [obj])
...
# .next() pulls the first object out of the generator
# .object retrieves django object the object from the DeserializedObject
obj = next(serializers.deserialize("json", serial)).object

It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.

我是这么做的:

首先,我使用demjson进行转换。它碰巧是我最先发现的,但它可能不是最好的。我的实现取决于它的一个特性,但其他转换器应该也有类似的方法。

其次,在所有可能需要序列化的模型上实现json_equivalent方法。对于demjson来说,这是一个神奇的方法,但无论您选择什么实现,都可能需要考虑这一点。这个想法是你返回一个对象,可以直接转换为json(即一个数组或字典)。如果你真的想自动执行:

def json_equivalent(self):
    dictionary = {}
    for field in self._meta.get_all_field_names()
        dictionary[field] = self.__getattribute__(field)
    return dictionary

这对你没有帮助,除非你有一个完全扁平的数据结构(没有foreignkey,数据库中只有数字和字符串等)。否则,您应该认真考虑实现此方法的正确方法。

第三,调用demjson.JSON.encode(instance),你就得到了你想要的东西。

似乎你不能序列化实例,你必须序列化一个对象的QuerySet。

from django.core import serializers
from models import *

def getUser(request):
    return HttpResponse(json(Users.objects.filter(id=88)))

我运行了django的svn释放,所以这可能不是在早期版本。

使用列表,它将解决问题

步骤1:

 result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all();

步骤2:

 result=list(result)  #after getting data from model convert result to list

步骤3:

 return HttpResponse(json.dumps(result), content_type = "application/json")
ville = UneVille.objects.get(nom='lihlihlihlih')
....
blablablab
.......

return HttpResponse(simplejson.dumps(ville.__dict__))

我返回我实例的字典

所以它会返回类似{'field1':value,"field2":value,....}