Django Rest Framework POST更新(如果已存在或已创建) [英] Django Rest Framework POST Update if existing or create

查看:277
本文介绍了Django Rest Framework POST更新(如果已存在或已创建)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是DRF的新手。
我阅读了API文档,也许很明显,但是我找不到方便的方法。

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.

我有一个Answer对象,它一对一与问题的关系。

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

在正面,我曾经使用POST方法创建发送到api / answers的答案,并使用PUT方法更新发送到例如api / answers / 24

On the front side I used to use POST method to create an answer sent to api/answers, and PUT method to update sent to e.g. api/answers/24

但是我想在服务器端进行处理。我只会向api / answers发送POST方法,并且DRF将基于answer_id或question_id(因为它是一对一的)检查对象是否存在。
如果这样做,它将更新现有的,如果不是,它将创建一个新的答案。

But I want to handle it on the server side. I will only send a POST method to api/answers and DRF will check based on answer_id or question_id (since it is one to one) if the object exists. If it does, it will update the existing one, if it doesn't it will create a new answer.

我应该在哪里实现,我不知道。

Where I should implement it, I couldn't figure out. Overriding create in serializer or in ViewSet or something else?

下面是我的模型,序列化器和视图:

Here are my model, serializer and view:

class Answer(models.Model):
    question = models.OneToOneField(
        Question, on_delete=models.CASCADE, related_name="answer"
    )
    answer = models.CharField(
        max_length=1, choices=ANSWER_CHOICES, null=True, blank=True
    )


class AnswerSerializer(serializers.ModelSerializer):
    question = serializers.PrimaryKeyRelatedField(
        many=False, queryset=Question.objects.all()
    )

    class Meta:
        model = Answer
        fields = ("id", "answer", "question")


class AnswerViewSet(ModelViewSet):
    queryset = Answer.objects.all()
    serializer_class = AnswerSerializer
    filter_fields = ("question", "answer")


推荐答案

很遗憾,您提供并接受的答案不能回答您的原始问题,因为它不会更新模型。但是,这可以通过另一种便捷方法轻松实现: update-或创建

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

这应该在数据库中创建 Answer 对象如果没有 question = validated_data ['question'] 的答案,而从 validated_data ['answer'] 。如果已经存在,django会将其答案属性设置为 validated_data ['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'].

Nirri的答案,此函数应驻留在序列化器中。如果您使用通用的 ListCreateView ,它将调用发送发布请求后创建函数并生成相应的响应。

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.

这篇关于Django Rest Framework POST更新(如果已存在或已创建)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆