创建或更新(使用PUT)在Django的REST框架 [英] Create or Update (with PUT) in Django Rest Framework

查看:786
本文介绍了创建或更新(使用PUT)在Django的REST框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有其中有一个模型有一个主键 ID = models.UUIDField(primary_key = True,则默认值= uuid.uuid4,编辑= FALSE)

I have a model which has has an primary key id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False).

PUT 请求发送到资源的端点 /api/v1/resource/<id>.json 我想的创建的使用提供的 ID的新资源如果资源不存在。

When a PUT request is sent to the resource's endpoint /api/v1/resource/<id>.json I would like to create a new resource with the supplied id if the resource does not already exist.

注:我使用的是 ModelViewSet ModelSerializer

什么是这样做的最优雅的方式?

What is the most elegant way of doing this?

推荐答案

我结束了覆盖在的get_object()方法我 ModelViewSet

I ended up overriding the get_object() method in my ModelViewSet:

class ResourceViewSet(viewsets.ModelViewSet):
    """
    This endpoint provides `create`, `retrieve`, `update` and `destroy` actions.
    """
    queryset = Resource.objects.all()
    serializer_class = ResourceSerializer

    def get_object(self):
        if self.request.method == 'PUT':
            resource = Resource.objects.filter(id=self.kwargs.get('pk')).first()
            if resource:
                return resource
            else:
                return Resource(id=self.kwargs.get('pk'))
        else:
            return super(ResourceViewSet, self).get_object()

也许有这样做的更优雅的方式?

Perhaps there's a more elegant way of doing this?

这篇关于创建或更新(使用PUT)在Django的REST框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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