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


当前回答

这是一个项目,它可以序列化(JSON基础现在)你的模型中的所有数据,并将它们自动放在一个特定的目录,然后它可以在你想要的任何时候反序列化它…我个人用这个脚本序列化了数千条记录,然后将它们全部加载回另一个数据库,而没有丢失任何数据。

任何对开源项目感兴趣的人都可以贡献这个项目,并为其添加更多特性。

serializer_deserializer_model

其他回答

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),你就得到了你想要的东西。

如果你想将单个模型对象作为json响应返回给客户端,你可以做这个简单的解决方案:

from django.forms.models import model_to_dict
from django.http import JsonResponse

movie = Movie.objects.get(pk=1)
return JsonResponse(model_to_dict(movie))

使用python格式的Django Serializer,

from django.core import serializers

qs = SomeModel.objects.all()
serialized_obj = serializers.serialize('python', qs)

json和python格式有什么区别?

json格式将以str格式返回结果,而python将以list或OrderedDict格式返回结果

下面是我的解决方案,它允许您轻松地自定义JSON以及组织相关记录

首先在模型上实现一个方法。我调用的是json,但你可以叫它任何你喜欢的,例如:

class Car(Model):
    ...
    def json(self):
        return {
            'manufacturer': self.manufacturer.name,
            'model': self.model,
            'colors': [color.json for color in self.colors.all()],
        }

然后在视图中:

data = [car.json for car in Car.objects.all()]
return HttpResponse(json.dumps(data), content_type='application/json; charset=UTF-8', status=status)

所有这些答案与我对框架的期望相比都有点俗气,我认为到目前为止,如果你使用的是rest框架,最简单的方法是:

rep = YourSerializerClass().to_representation(your_instance)
json.dumps(rep)

这将直接使用Serializer,尊重您在其上定义的字段,以及任何关联等等。