我正在使用DRF作为我的API后端。我需要在一个帖子请求中插入多个对象。我看到了很多教程,How do I create multiple model instances with Django Rest Framework?,但没有成功。我正在使用ModelSerializer,但是当使用 many = True 时,则会遇到ListSerializer的问题。
views.py
class SaleUserViewSet(ModelViewSet):
queryset = SaleUser.objects.all()
serializer_class = SaleUserSerializer(many=True)
serlializers.py
class SaleUserSerializer(serializers.ModelSerializer):
class Meta:
model = SaleUser
fields = ('id', 'comment', 'creation_date', 'modification_date', 'last_user', 'user', 'sale', 'user_sale_type')
错误消息
/ api / sale_user / type object中的AttributeError' Meta'没有属性'模型'
请告知。
答案 0 :(得分:2)
将序列化程序回滚到默认值
class SaleUserSerializer(serializers.ModelSerializer):
class Meta:
model = SaleUser
fields = ('id', 'comment', 'creation_date', 'modification_date', 'last_user', 'user', 'sale', 'user_sale_type')
并覆盖视图:
class SaleUserViewSet(ModelViewSet):
queryset = SaleUser.objects.all()
serializer_class = SaleUserSerializer
def create(self, request, *args, **kwargs):
data = request.data.get("items") if 'items' in request.data else request.data
many = isinstance(data, list)
print (data, many)
serializer = self.get_serializer(data=data, many=many)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)