Disable creating nested objects in django rest framework

后端 未结 3 1206
孤城傲影
孤城傲影 2021-02-09 14:52

Hi,

Can you help me how to disable creating nested objects ?

I have serializers like this:
(Employee has ForeignKey to Team) <

3条回答
  •  不知归路
    2021-02-09 15:04

    I found that ModelSerializer.to_native() and ModelSerializer.from_native() don't exist in the latest version of DRF. I came up with the following derived from the accepted solution:

    class PlayerSerializer(serializers.ModelSerializer):
        class Meta:
            model = Player
            fields = ('id', 'name', 'team')
    
        def to_internal_value(self, data):
            # If team is not a dict, such as when submitting via the Browseable UI, this would fail.
            try:
                data['team'] = data['team']['id']
            except TypeError:
                pass
            return super(PlayerSerializer, self).to_internal_value(data)
    
        def to_representation(self, instance):
            return ReadPlayerSerializer(instance).data
    
    
    class ReadPlayerSerializer(serializers.ModelSerializer):
        team = TeamSerializer()
    
        class Meta(PlayerSerializer.Meta):
            pass
    

    Effectively, it seems that from_native is now to_representation, and to_native is no to_internal_value

提交回复
热议问题