Django Rest Framework POST Update if existing or create

前端 未结 8 1835
余生分开走
余生分开走 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:06

    Unfortunately your provided and accepted answer does not answer your original question, since it does not update the model. This however is easily achieved by another convenience method: update-or-create

    def create(self, validated_data):
        answer, created = Answer.objects.update_or_create(
            question=validated_data.get('question', None),
            defaults={'answer': validated_data.get('answer', None)})
        return answer
    

    This should create an Answer object in the database if one with question=validated_data['question'] does not exist with the answer taken from validated_data['answer']. If it already exists, django will set its answer attribute to validated_data['answer'].

    As noted by the answer of Nirri, this function should reside inside the serializer. If you use the generic ListCreateView it will call the create function once a post request is sent and generate the corresponding response.

提交回复
热议问题