简体   繁体   English

如何在django / python中将JSON模型对象列表序列化为JSON

[英]How to serialize to JSON a list of model objects in django/python

I am trying to serialize a list of model object defined as: 我正在尝试序列化定义为的模型对象列表:

class AnalysisInput(models.Model):
    input_user = models.CharField(max_length=45)
    input_title = models.CharField(max_length=45)
    input_date = models.DateTimeField()
    input_link = models.CharField(max_length=100)

I wrote a custom serializer (encoder) for json.dumps(): 我为json.dumps()编写了一个自定义序列化器(编码器):

class AnalysisInputEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AnalysisInput):
            return { "input_id" : obj.id,
                    "input_user" : obj.input_user,
                    "input_title" : obj.input_title,
                    "input_date" : obj.input_date.isoformat(),
                    "input_link" : obj.input_link }
        return json.JSONEncoder.default(self, obj)

When I serialize only one object, I am able to do it. 当我只序列化一个对象时,我能够做到。 When I try to serialize a list of object I get 当我尝试序列化我得到的对象列表时

[ objects..] is not JSON serializable

I searched but I didn't find where to work on.. I was thinking about writing a custom serializer also for list of model object. 我搜索但我没有找到工作的地方..我正在考虑为模型对象列表编写自定义序列化器。

A custom encoder is not called recursively. 自定义编码器不会递归调用。 You are actually better off not using a custom encoder, and instead convert your objects to simple python types before serializing. 实际上,最好使用自定义编码器,而是在序列化之前将对象转换为简单的python类型。

You could add a as_json or similarly named method to your model and calling that every time you need a JSON result: 您可以向模型添加as_json或类似命名的方法,并在每次需要JSON结果时调用它:

class AnalysisInput(models.Model):
    input_user = models.CharField(max_length=45)
    input_title = models.CharField(max_length=45)
    input_date = models.DateTimeField()
    input_link = models.CharField(max_length=100)

    def as_json(self):
        return dict(
            input_id=self.id, input_user=self.input_user,
            input_title=self.input_title, 
            input_date=self.input_date.isoformat(),
            input_link=self.input_link)

Then in your view: 然后在你看来:

# one result
return HttpResponse(json.dumps(result.as_json()), content_type="application/json")

# a list of results
results = [ob.as_json() for ob in resultset]
return HttpResponse(json.dumps(results), content_type="application/json")

The best way I found to serialize your Django models is by using django.core.serializers to serialize your model list into JSON, XML, or YAML. 我发现序列化Django模型的最好方法是使用django.core.serializers将模型列表序列化为JSON,XML或YAML。 No custom serialization code required! 无需自定义序列化代码! Documentation is here: https://docs.djangoproject.com/en/dev/topics/serialization/ 文档在这里: https//docs.djangoproject.com/en/dev/topics/serialization/

Here is my implementation: 这是我的实现:

lead/models.py: 铅/ models.py:

from django.db import models

class Lead(models.Model):
    name = models.CharField(max_length=50)
    email = models.CharField(max_length=256)
    phone = models.CharField(max_length=20)
    twitter_handle = models.CharField(max_length=20)
    github_handle = models.CharField(max_length=20)

lead/views.py: 铅/ views.py:

from django.http import HttpResponse
from django.core import serializers
from lead.models import Lead

def index(request):
    leads_as_json = serializers.serialize('json', Lead.objects.all())
    return HttpResponse(leads_as_json, content_type='json')

The end result: 最终结果:

[{"pk": 1, "model": "lead.lead", "fields": {"twitter_handle": "johndoe", "name": "John Doe", "phone": "1(234)567-8910", "email": "john@doe.com", "github_handle": "johndoe"}}]

Simplest solution: 最简单的解决方案

def index(request):
    data = serializers.serialize('json', Product.objects.all())
    return HttpResponse(data, content_type='application/json')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM