Disable creating nested objects in django rest framework

后端 未结 3 1205
孤城傲影
孤城傲影 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 14:59

    Solved problem:

    class ReadEmployeeSerializer(serializers.ModelSerializer):
        team = TeamSerializer()
    
        class Meta:
            model = Employee
            fields = ('id', 'name', 'surname', 'team',)
    
    
    class WriteEmployeeSerializer(serializers.ModelSerializer):
    
        def from_native(self, data, files):
            data['team'] = data['team']['id']
            return serializers.ModelSerializer.from_native(self, data, files)
    
        def to_native(self, obj):
            return ReadEmployeeSerializer(obj).data
    
        class Meta:
            model = Employee
            fields = ('id', 'name', 'surname', 'team',)
    

    post/put method use primary key (WriteEmployeeSerializer) - before replace dict to primary key

    get method use full object (ReadEmployeeSerializer)

提交回复
热议问题