如何将JSON序列化到django / python中的模型对象列表 [英] How to serialize to JSON a list of model objects in django/python

查看:137
本文介绍了如何将JSON序列化到django / python中的模型对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 )

我为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)

当我只序列化一个对象时,我能够做到这一点当我尝试序列化一个对象列表时,我得到

  [objects ..]不是JSON可序列化

我搜索,但没有找到在哪里工作..我正在考虑编写一个自定义序列化器也列出模型

解决方案

定制编码器不是递归调用。您实际上更好的使用自定义编码器,而不是使用自定义编码器,而是在序列化之前将对象转换为简单的python类型。



您可以添加一个 as_json 或类似命名的方法,并在每次需要JSON结果时调用该方法:

 code> 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)

然后在您的视图中:

 #one result 
return HttpResponse(json.dumps(result.as_json()),content_type =appl ation / json)

#一个结果列表
results = [ob.as_json()for ob在结果集中]
return HttpResponse(json.dumps(results),content_type =application / json)


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():

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.

You could add a as_json or similarly named method to your model and calling that every time you need a JSON result:

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")

这篇关于如何将JSON序列化到django / python中的模型对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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