django rest framework abstract class serializer

后端 未结 4 975
名媛妹妹
名媛妹妹 2021-02-07 05:01

I have some models like these:

class TypeBase(models.Model):
    name = models.CharField(max_length=20)
    class Meta:
        abstract=True

class PersonType(T         


        
4条回答
  •  星月不相逢
    2021-02-07 05:21

    Just iterating a bit over @adki's answer:

    1. it is possible to skip model for TypeBaseSerializer;
    2. derived serializers can refer to TypeBaseSerializer.Meta, so you would change them in a single place.
    class TypeBaseSerializer(serializers.Serializer):
        class Meta:
            fields = ('id', 'name', 'created')
            abstract = True
    
        def func(...):
        # ... some logic
    
    class PersonTypeSerializer(TypeBaseSerializer):
        class Meta:
            model = PersonType
            fields = TypeBaseSerializer.Meta.fields + ('age', 'date_of_birth')
    
    class CompanyTypeSerializer(TypeBaseSerializer):
        class Meta:
            model = CompanyType
            fields = TypeBaseSerializer.Meta.fields
    

提交回复
热议问题