Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过驻留在另一个序列化程序中序列化列表_Python_Django_Serialization_Django Rest Framework - Fatal编程技术网

Python 通过驻留在另一个序列化程序中序列化列表

Python 通过驻留在另一个序列化程序中序列化列表,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,这是我的输出,应该是 { "status": 1, "errors": "", "results": [ { "car_type": "sedan", "is_active": true, "company": { ["tata","hyundai"] } } ] } 我的模型是 class CarTyp

这是我的输出,应该是

{
    "status": 1,
    "errors": "",
    "results": [
        {
            "car_type": "sedan",
            "is_active": true,
            "company": {
                ["tata","hyundai"]
            }
        }
    ]
}
我的模型是

class CarType(CommonBase):
    car_type = models.TextField(null=True, blank=True)
    is_active = models.BooleanField(default=True)
    company = models.ManyToManyField('Company', null=True,
                                      blank=True)


class Company(CommonBase):
    company_name = models.TextField(null=True, blank=True)
    country = models.TextField(null=True, blank=True)
我应该如何编写我的serialiser for get API,以返回所有带有
的汽车类型,即

{
     "company": {[...]}
}
公司序列化中的字典内容没有意义,相反,你想要的是一个实际的列表

只关注
结果中的项序列化
可以使用如下序列化程序:

class CarTypeSerializer(serializers.ModelSerializer):
    company = serializers.SerializerMethodField()

    def get_company(self, obj):
        return [company.company_name for company in obj.company.all()]

    class Meta:
        model = CarType
        fields = ("car_type", "is_active", "company")
这将产生如下输出:

{
    "car_type": "Car type..",
    "is_active": true,
    "company": [
        "company 1",
        "company 2"
    ]
}

您可以在queryset方法中的views.py中进行筛选,我已经完成了。但问题是,我只在
公司
中获取ID,而不是它的名称。它的输出类似于
{“状态”:1,“错误”:“结果”:[{“汽车类型”:“轿车”,“是否处于活动状态”:true,“公司”:{1,2}}}