gpt4 book ai didi

django - 使用 Django Rest Framework 的 ListSerializer 批量创建

转载 作者:行者123 更新时间:2023-12-01 09:47:21 30 4
gpt4 key购买 nike

我正在尝试使用 Django Rest Framework 为某个表批量创建行。我在 documentation 中看到DRF 支持它。

View .py

class UserProfileFeedViewSet(viewsets.ModelViewSet):
"""Handles creating, reading and updating profile feed items."""

authentication_classes = (TokenAuthentication,)
queryset = models.ProfileFeedItem.objects.all()
serializer_class = serializers.ProfileFeedItemSerializer(queryset, many=True)
permission_classes = (permissions.PostOwnStatus, IsAuthenticated)

def perform_create(self, serializer):
"""Sets the user profile to the logged in user."""

serializer.save(user_profile=self.request.user)

序列化程序.py
class ProfileFeedItemListSerializer(serializers.ListSerializer):
def create(self,validated_data):
feed_list = [ProfileFeedItem(**item) for item in validated_data]
return ProfileFeedItem.objects.bulk_create(feed_list)

class ProfileFeedItemSerializer(serializers.ModelSerializer):
"""A serializer for profile feed items."""

class Meta:
model = models.ProfileFeedItem
list_serializer_class = ProfileFeedItemListSerializer
fields = ('id', 'user_profile', 'status_text', 'created_on')
extra_kwargs = {'user_profile': {'read_only': True}}

当我尝试使用管理表单发帖时,我总是收到此错误。你能帮我确定我在这里做错了什么吗?

TypeError at /api/feed/ 'ProfileFeedItemListSerializer' object is not callable Request Method: GET Request URL: http://127.0.0.1:8080/api/feed/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'ProfileFeedItemListSerializer' object is not callable Exception Location: /home/ubuntu/.virtualenvs/profiles_api/local/lib/python3.5/site-packages/rest_framework/generics.py in get_serializer, line 111 Python Executable: /home/ubuntu/.virtualenvs/profiles_api/bin/python Python Version: 3.5.2

最佳答案

尝试一下:

def create(self, request, *args, **kwargs):
many = isinstance(request.data, list)
serializer = self.get_serializer(data=request.data, many=many)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, headers=headers)

def perform_create(self, serializer):
if type(serializer.validated_data) == list:
for item in serializer.validated_data:
item.update({'user_profile': self.request.user})
else:
serializer.validated_data.update({'user_profile': self.request.user})
serializer.save()

不幸的是,现在我无法检查解决方案,但也许它会给出正确的方法

关于django - 使用 Django Rest Framework 的 ListSerializer 批量创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917656/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com