Change a field in a Django REST Framework ModelSerializer based on the request type?

后端 未结 5 2451
半阙折子戏
半阙折子戏 2021-02-19 08:13

Consider this case where I have a Book and Author model.

serializers.py

class AuthorSerializer(serializers.ModelSerializer):

         


        
5条回答
  •  醉酒成梦
    2021-02-19 09:07

    The way I ended up dealing with this problem was having another serializer for when it's a related field.

    class HumanSerializer(PersonSerializer):
    
        class Meta:
            model = Human
            fields = PersonSerializer.Meta.fields + (
                'firstname',
                'middlename',
                'lastname',
                'sex',
                'date_of_birth',
                'balance'
            )
            read_only_fields = ('name',)
    
    
    class HumanRelatedSerializer(HumanSerializer):
        def to_internal_value(self, data):
            return self.Meta.model.objects.get(id=data['id'])
    
    
    class PhoneNumberSerializer(serializers.ModelSerializer):
        contact = HumanRelatedSerializer()
    
        class Meta:
            model = PhoneNumber
            fields = (
                'id',
                'contact',
                'phone',
                'extension'
            )
    

    You could do something like this, but for the RelatedSerializer do:

     def to_internal_value(self, data):
         return self.Meta.model.objects.get(id=data)
    

    Thus, when serializing, you serialize the related object, and when de-serializing, you only need the id to get the related object.

提交回复
热议问题