如果将many = true作为参数传递,则无法为我的django序列化程序自定义响应数据

时间:2015-12-10 08:49:26

标签: django serialization django-rest-framework

如果我通过response.data,我无法为我正在使用的序列化程序自定义many=True

以下是我用于序列化组织数据的序列化程序。

serializers.py

class OrganizationSerializer(ModelSerializer):
    # fields

    class Meta:
        model = Organization
        fields = ('name',)

    @property
    def data(self):
        request = self.context['request']
        href = request.build_absolute_uri()  
        ret = super(OrganizationSerializer, self).data        
        # Below i am customizing serializer data based on my specific
        #    requirement. 
        ret = {'href':href, 'items':ret}
        return ReturnDict(ret, serializer=self)

views.py。

# view code ---
organizations = Organization.objects.all()
response = OrganizationSerializer(organizations[0], context={'request':request})
return response.data

我可以response.data获得{'href': '<url>', 'items': {}] 根据我们的代码。

但是当我在下面做 -

organizations = Organization.objects.all()
serializer = OrganizationSerializer(organizations, many=True, context={'request':request})

我无法将response.data作为{'href': '<url>', 'items': {}]。 我希望使用或不使用many = True来响应我的response.data。

我查看了serializers.py(django rest app)的源代码,发现如果将many = true作为参数传递,则ListSerializer将用于返回序列化数据。

修改:

models.py

class Organization(models.Model):
    name = models.CharField(max_length=20)

2 个答案:

答案 0 :(得分:0)

我认为您可以使用 SerializerMethodField 格式化数据,然后使用 Meta 类来指定要返回的字段,因此根据您的代码段逻辑,解决方案应如下所示:

FieldMustBeDate
FieldMustBeNumeric
PropertyValueInvalid
PropertyValueRequired

检查SerializerMethodField Doc

答案 1 :(得分:0)

我通过覆盖many_init方法解决了这个问题。

class OrganizationSerializer(ModelSerializer):
    # fields

    class Meta:
        model = Organization
        fields = ('name',)

    @property
    def data(self):
        # come into action when.
        # response = OrganizationSerializer(organizations[0], context={'request':request})         
        request = self.context['request']
        href = request.build_absolute_uri()  
        ret = super(OrganizationSerializer, self).data        
        # Below i am customizing serializer data based on my specific
        #    requirement. 
        ret = {'href':href, 'items':ret}
        return ReturnDict(ret, serializer=self)

    @classmethod
    def many_init(cls, *args, **kwargs):
        # come into action when 
        #response = OrganizationSerializer(organizations, many=True, context={'request':request})
        res = super(OrganizationSerializer, cls).many_init(*args, **kwargs)            
        request = kwargs['context']['request']
        href = request.build_absolute_uri()                   
        res.items = {'href': href, 'items': res.data}
        return res