Django使用字段约束更新模型形式

时间:2019-02-20 10:50:46

标签: django django-rest-framework

具有以下模型:

class Book(models.Model):
    name = models.CharField()
    author = models.CharField()
    date = models.DateField()

    class Meta:
        unique_together = ('name', 'author')

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

class BookView(ApiView):

    def put(self, request, *args, **kwargs):
        serializer = BookSerializerWrite(data=request.data)
        if serializer.is_valid():
            serializer.save()

由于serializer.is_valid()False,因此上面的视图不起作用。 消息是:

'The fields name, author must make a unique set'

哪个是模型的约束。

如何更新模型?

我宁愿不重写序列化程序的验证方法。

我也无法访问validated_data进行更新,如

https://www.django-rest-framework.org/api-guide/serializers/#saving-instances

,因为表单未通过验证,因此该字段为空。 有内置的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以使用UpdateAPIview

实现它

serializers.py

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('name', 'author', 'date')

views.py

from rest_framework.generics import UpdateAPIview
from .serializers import BookSerializer

class BookUpdateView(UpdateAPIView):
   serializer_class = BookSerializer

urls.py

from django.urls import path
from . import views

url_patterns = [
    path('api/book/<int:pk>/update/', views.BookUpdateView.as_view(), name="book_update"),
]

现在,将您的数据发布到以上url。应该可以。

参考:https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py