如何覆盖 POST 批量添加方法 - Django Rest Framework
How to override POST method for bulk adding - Django Rest Framework
我正在使用 Django Rest Framework 编写 REST API,我希望我的其中一条路线接受批量添加 POST 方法,以创建多个对象。其他方法(GET、PUT、PATCH、DELETE)仍将保持不变,一次只接受一个。
目前我所拥有的如下,目前可以一次发布一个。
在我的 urls.py:
path('book', books.BookViewSet.as_view()),
books.py:
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
queryset = Book.objects.all()
permission_classes = (IsAuthenticated, )
serializer.py:
class BookSerializer(serializers.ModelSerializer):
def create(self, validated_data):
# I assume this is the method to be overridden to get this
class Meta:
model = Book
fields = ('id', 'name', 'author_id', 'page_number', 'active')
Serializer 创建方法,不幸的是通过 object.You 创建数据对象可以覆盖 ModelViewSet
的创建方法,并在验证后使用 bulk_create
方法。
def create(self, request, *args, **kwargs):
many = True if isinstance(request.data, list) else False
serializer = BookSerializer(data=request.data, many=many)
serializer.is_valid(raise_exception=True)
author = request.user # you can change here
book_list = [Book(**data, author=author) for data in serializer.validated_data]
Book.objects.bulk_create(book_list)
return Response({}, status=status.HTTP_201_CREATED)
我正在使用 Django Rest Framework 编写 REST API,我希望我的其中一条路线接受批量添加 POST 方法,以创建多个对象。其他方法(GET、PUT、PATCH、DELETE)仍将保持不变,一次只接受一个。
目前我所拥有的如下,目前可以一次发布一个。
在我的 urls.py:
path('book', books.BookViewSet.as_view()),
books.py:
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
queryset = Book.objects.all()
permission_classes = (IsAuthenticated, )
serializer.py:
class BookSerializer(serializers.ModelSerializer):
def create(self, validated_data):
# I assume this is the method to be overridden to get this
class Meta:
model = Book
fields = ('id', 'name', 'author_id', 'page_number', 'active')
Serializer 创建方法,不幸的是通过 object.You 创建数据对象可以覆盖 ModelViewSet
的创建方法,并在验证后使用 bulk_create
方法。
def create(self, request, *args, **kwargs):
many = True if isinstance(request.data, list) else False
serializer = BookSerializer(data=request.data, many=many)
serializer.is_valid(raise_exception=True)
author = request.user # you can change here
book_list = [Book(**data, author=author) for data in serializer.validated_data]
Book.objects.bulk_create(book_list)
return Response({}, status=status.HTTP_201_CREATED)