Django Rest Framework部分更新 [英] Django Rest Framework partial update

查看:706
本文介绍了Django Rest Framework部分更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过实现 partial_update Django Rest Framework ,但我需要澄清一下,因为我被卡住了。

I'm trying to implement partial_update with Django Rest Framework but I need some clarification because I'm stuck.


  1. 为什么我们需要指定partial = True?

    据我所知,我们可以轻松地在 partial_update 方法内更新Demo对象。

  1. Why do we need to specify partial=True?
    In my understanding, we could easily update Demo object inside of partial_update method. What is the purpose of this?

序列化变量的内容是什么?

内容是什么? partial_update 方法中的序列化变量?那是一个演示对象吗?幕后叫什么功能?

What is inside of serialized variable?
What is inside of serialized variable in partial_update method? Is that a Demo object? What function is called behind the scenes?




Viewset

Viewset



class DemoViewSet(viewsets.ModelViewSet):
    serializer_class = DemoSerializer

    def partial_update(self, request, pk=None):
        serialized = DemoSerializer(request.user, data=request.data, partial=True)
        return Response(status=status.HTTP_202_ACCEPTED)




序列化器

Serializer



class DemoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Demo
        fields = '__all__'

    def update(self, instance, validated_data):
        print 'this - here'
        demo = Demo.objects.get(pk=instance.id)
        Demo.objects.filter(pk=instance.id)\
                           .update(**validated_data)
        return demo


推荐答案

与您之前的问题相同,但是当我深入研究rest_framework的源代码时,我得到以下发现,希望对您有所帮助:

I have the same questions as yours before, but when I dig into the source code of rest_framework, I got the following findings, hope it would help:

此问题与 HTTP动词

PUT : PUT方法用请求有效负载替换目标资源的所有当前表示形式。

PUT: The PUT method replaces all current representations of the target resource with the request payload.

PATCH :PATCH方法是

PATCH: The PATCH method is used to apply partial modifications to a resource.

通常来说, partial 用于检查资源中的字段客户端向视图提交数据时,需要模型进行字段验证。

Generally speaking, partial is used to check whether the fields in the model is needed to do field validation when client submitting data to the view.

例如,我们有一本 Book 像这样的模特s,请注意,名称 author_name 字段均为必填(不为null和;

For example, we have a Book model like this, pls note both of the name and author_name fields are mandatory (not null & not blank).

class Book(models.Model):
    name = models.CharField('name of the book', max_length=100)
    author_name = models.CharField('the name of the author', max_length=50)

# Create a new instance for testing
Book.objects.create(name='Python in a nut shell', author_name='Alex Martelli')

在某些情况下,我们可能只需要更新模型中的部分字段,例如,我们只需要更新 Book <中的 name 字段。因此,在这种情况下,客户端将只向视图提交具有新值的 name 字段。从客户端提交的数据可能看起来像这样:

For some scenarios, We may only need to update part of the fields in the model, e.g., we only need to update name field in the Book. So for this case, client will only submit the name field with new value to the view. The data submit from the client may look like this:

{"pk": 1, name: "PYTHON IN A NUT SHELL"}

但是您可能已经注意到我们的模型定义不允许 author_name 为空白。因此,我们必须使用 partial_update ,而不是 update 。因此,其余框架将不会对请求数据中缺少的字段执行字段验证检查

But you may have notice that our model definition does not allow author_name to be blank. So we have to use partial_update instead of update. So the rest framework will not perform field validation check for the fields which is missing in the request data.

出于测试目的,您可以创建 update partial_update 的两个视图,您将更加理解我刚才说的话。

For testing purpose, you can create two views for both update and partial_update, and you will get more understanding what I just said.

from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book


class BookUpdateView(GenericAPIView, UpdateModelMixin):
    '''
    Book update API, need to submit both `name` and `author_name` fields
    At the same time, or django will prevent to do update for field missing
    '''
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

class BookPartialUpdateView(GenericAPIView, UpdateModelMixin):
    '''
    You just need to provide the field which is to be modified.
    '''
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def put(self, request, *args, **kwargs):
        return self.partial_update(request, *args, **kwargs)



urls.py

urls.py

urlpatterns = patterns('',
    url(r'^book/update/(?P<pk>\d+)/$', BookUpdateView.as_view(), name='book_update'),
    url(r'^book/update-partial/(?P<pk>\d+)/$', BookPartialUpdateView.as_view(), name='book_partial_update'),
)

要提交的数据

{"pk": 1, name: "PYTHON IN A NUT SHELL"}

将上述json提交到 / book / update / 1 / ,您将收到HTTP_STATUS_CODE = 400的以下错误:

When you submit the above json to the /book/update/1/, you will got the following error with HTTP_STATUS_CODE=400:

{
  "author_name": [
    "This field is required."
  ]
}

但是当您将上述json提交给 / book / update-partial / 1 / ,您将获得HTTP_STATUS_CODE = 200并显示以下响应,

But when you submit the above json to /book/update-partial/1/, you will got HTTP_STATUS_CODE=200 with following response,

{
  "id": 1,
  "name": "PYTHON IN A NUT SHELL",
  "author_name": "Alex Martelli"
}



问题2。序列化变量的内容是什么?



serialized 是将模型实例包装为可序列化对象的对象。并且您可以使用此序列化生成带有 serialized.data 的纯JSON字符串。

For question 2. What is inside of serialized variable?

serialized is a object wrapping the model instance as a serialisable object. and you can use this serialized to generate a plain JSON string with serialized.data .

我想您可以在阅读以上答案后回答自己,并且应该知道何时使用更新以及何时使用 partial_update

I think you can answer yourself when you have read the answer above, and you should have known when to use update and when to used partial_update.

如果您还有任何疑问,请随时提问。我只是阅读了rest框架的部分源代码,可能对某些术语没有很深入的了解,请指出错误的地方...

If you still have any question, feel free to ask. I just read part of the source odes of rest framework, and may have not understand very deeply for some terms, and please point it out when it is wrong...

这篇关于Django Rest Framework部分更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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