简体   繁体   中英

DRF serializer depth makes fields ignored on create

(project is available on github with that problem)

For some reason serializer's depth option makes fields ignored on create.

Serializer:

class AnswerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Answer
        fields = ('question', 'body',)
        depth = 1

View:

class AnswerList(ListCreateAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerSerializer

When I try to create an answer with depth = 1 I get NOT NULL constraint failed: forum_answer.question_id , but when I comment out depth = 1 everything works. But of course I don't get a full Question object, only pk of it.

Found a better solution here

Now serializer looks like that:

class AnswerSerializer(serializers.ModelSerializer):
    question_pk = serializers.PrimaryKeyRelatedField(
        queryset=Question.objects.all(), source='question', write_only=True
    )

    class Meta:
        model = Answer
        fields = ('question', 'question_pk', 'body',)
        depth = 1

ps. Also commited to the project on github.

IMPORTANT: I believe this method is very UNSECURE because anyone can edit nested objects.

You can use drf-writable-nested for such functionality. Updated the project on github if someone needs.

ps. be sure to use 'pk' field for nested objects if you don't want these objects to be created.

class DemoSerializer(serializers.ModelSerializer):
def __init__(self, instance=None, data=empty, **kwargs):
    if instance:
        setattr(self.Meta, 'depth', 1)
    else:
        setattr(self.Meta, 'depth', 0)
    super(DemoSerializer, self).__init__(instance, data, **kwargs)

class Meta:
    model = Demo
    fields = '__all__'
    depth = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM