Django Rest Framework POST Update if existing or create

前端 未结 8 1819
余生分开走
余生分开走 2020-12-13 09:24

I am new to DRF. I read the API docs, maybe it is obvious but I couldn\'t find a handy way to do it.

I have an Answer object which has one-to-one relationship with a

相关标签:
8条回答
  • 2020-12-13 10:11

    Also:

    try:
       serializer.instance = YourModel.objects.get(...)
    except YourModel.DoesNotExist:
       pass
    
    if serializer.is_valid():
       serializer.save()    # will INSERT or UPDATE your validated data
    
    0 讨论(0)
  • 2020-12-13 10:12

    I would use the serializers' create method.

    In it you could check if the question (with the ID of it you provide in the 'question' primary key related field) already has an answer, and if it does, fetch the object and update it, otherwise create a new one.

    So the first option would go something like:

    class AnswerSerializer(serializers.ModelSerializer):
        question = serializers.PrimaryKeyRelatedField(many=False, queryset=Question.objects.all())
    
        class Meta:
            model = Answer
            fields = (
                'id',
                'answer',
                'question',
            )
    
        def create(self, validated_data):
            question_id = validated_data.get('question', None)
            if question_id is not None:
                question = Question.objects.filter(id=question_id).first()
                if question is not None:
                    answer = question.answer
                    if answer is not None:
                       # update your answer
                       return answer
    
            answer = Answer.objects.create(**validated_data)
            return answer
    

    Second option would be to check if the answer with the answer id exists.

    Answer ID's wouldn't show up in the validated data of post requests, unless you used a sort of workaround and manually defined them as read_only = false fields:

    id = serializers.IntegerField(read_only=False)
    

    But you should however rethink this through, There's a good reason the PUT method and the POST methods exist as separate entities, and you should separate the requests on the frontend.

    0 讨论(0)
提交回复
热议问题