根据模型字段值动态创建序列化器

时间:2018-12-10 08:12:48

标签: django django-rest-framework

我有一个像这样的模型:

class A:
    name = models.CharField()
    group = models.ForeignKey('SomeModel', null=True, blank=True)

当我将此序列化时,我希望Serielizer根据“ group”字段是否为空白而具有不同的格式。当然,这可以通过为不同格式使用不同的序列化器并在View层中根据需要调用它们来实现:

class TypeASerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name')

class TypeBSerializer(serializers.ModelSerializer)

    class Meta:
        model = A
        fields = ('id', 'name', 'group')

但是我想在序列化器层本身中处理它,为此有一个序列化器。有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以覆盖序列化器的get_fields方法

class YourSerializer(serializers.ModelSerializer):
   id = serializers.SerializerMethodField()
   name = serializers.SerializerMethodField()
   group = serializers.SerializerMethodField()

   class Meta:
      model = A
      fields = ('id', 'name', 'group')

   def get_fields(self):
      fields = super().get_fields()
      # delete all the unnecessary fields according to your logic.
      if self.instance.group:  # if this is detials view other wise pass object in context
         del fields['group']
      return fields 

答案 1 :(得分:0)

您可以将序列化器的每个字段声明为SerializerMethodField,如下所示:

class YourSerializer(serializers.ModelSerializer):
    id = serializers.SerializerMethodField()
    name = serializers.SerializerMethodField()
    group = serializers.SerializerMethodField()

    class Meta:
        model = A
        fields = ('id', 'name', 'group')

    def id(self, obj):
        if yourcondition(obj.group):
            return obj.id
        return another_value
    ...