django rest framework abstract class serializer

后端 未结 4 969
名媛妹妹
名媛妹妹 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:43

    I think the following approach is more cleaner. You can set "abstract" field to true for the base serializer and add your common logic for all child serializers.

    class TypeBaseSerializer(serializers.ModelSerializer):
        class Meta:
            model = TypeBase
            fields = ('id', 'name')
            abstract = True
    
        def func(...):
        # ... some logic
    

    And then create child serializers and use them for data manipulation.

    class PersonTypeSerializer(TypeBaseSerializer):
        class Meta:
            model = PersonType
            fields = ('id', 'name')
    
    
    class CompanyTypeSerializer(TypeBaseSerializer):
        class Meta:
            model = CompanyType
            fields = ('id', 'name')
    

    Now you can use the both of these serializers normally for every model.

    But if you really want to have one serializers for both the models, then create a container model and a serializer for him too. That is much cleaner :)

提交回复
热议问题