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

查看:27
本文介绍了如何将 django/python 中的模型对象列表序列化为 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)

我为 json.dumps() 编写了一个自定义序列化器(编码器):

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.

推荐答案

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

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.

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

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)

那么在你看来:

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

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

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