Django REST |全局排除序列化程序中的某些字段

时间:2015-07-09 14:57:46

标签: python django django-rest-framework

有没有办法全局排除或包含所有模型中的某些字段?

我在所有模型上都有“active”,“created_time”,“updated_time”,“created_by”,“updated_by”等字段,除非在exclude中指定,否则这些字段会对响应产生额外负担。

有没有办法全局排除它们,除非在字段中指定?

2 个答案:

答案 0 :(得分:0)

这不是最干净的解决方案,但这是我通过继承和对父序列化程序的Meta类的具体引用来实现的:

class SampleSerializer(serializers.HyperlinkedModelSerializer):
    notes = MarkdownNoteSerializer(many=True,required=False,allow_add_remove=True)
    class Meta:
        model = Sample
        fields = ('url', 'creation_datetime', 'update_datetime','notes')

class RipeSampleSerializer(SampleSerializer):
    class Meta:
        model = RipeSample
        fields = SampleSerializer.Meta.fields + ( 'ripe', )

然后,您可以通过明确引用或不引用字段来包含或排除字段。

也没有理由不创建要包含在字段中的元组集:

SampleFields = ('foo', 'bar', 'baz')
OtherFields = ('update', 'creation')

[...]
fields = SampleFields + OtherFields + ('yahoo',)

答案 1 :(得分:0)

创建将覆盖get_fields方法的mixin:

class CustomFieldsMixin(object):
    def _get_exlude_fields(self):
        return ["active", "created_time", "updated_time", "created_by", "updated_by"]

    def _get_include_fields(self):
        return {"name": serializers.CharField()}

    def get_fields(self):
        fields = super(CustomFieldsMixin, self).get_fields()

        for exclude_field in self._get_exclude_fields():
            if exclude_field in fields:
                del field[fields]

        for include_field, include_field_value in self._get_include_fields().items():
            if include_field not in fields:
                 field[include_field] = include_field_value

        return fields

(这是代码只是基本概念的一个例子)

如果每个序列化器都使用mixin:

class SampleSerializer(CustomFieldsMixin, serializers.HyperlinkedModelSerializer)