我正在尝试使用django REST框架在名为cart的模型中添加多个对象。用户将多个cart对象数据发送到CartAddSerializer,序列化器将逐个添加数据库中的行。到目前为止我的代码进度如下:
models.py:
class Cart(models.Model):
user = models.ForeignKey(User)
product = models.ForeignKey(Product)
sh_price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.IntegerField()
date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Meta:
unique_together = ["user", "product"]
serializer.py:
class CartAddSerializer(ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(CartAddSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = Cart
fields = ['user', 'product', 'sh_price', 'quantity', 'date_added']
extra_kwargs = {'date_added': {'read_only': True},
'sh_price': {'read_only': True},}
def create(self, data):
product_data = data.get('product' or None)
print(product_data)
print(product_data.id)
product_price = ProductPrice.objects.get(product=product_data)
print(product_price)
print(product_price.sh_price)
return Cart.objects.create(sh_price=product_price.sh_price, **data)
views.py:
class CartAddAPIView(ListCreateAPIView):
queryset = Cart.objects.all()
serializer_class = CartAddSerializer
lookup_field = 'pk'
lookup_url_kwarg = 'id'
def get(self, request, *args, **kwargs):
try:
cart = Cart.objects.filter(user=self.kwargs['id'])
print(cart)
serializer = CartDetailSerializer(cart, many=True, context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
except Exception as e:
print(str(e))
return Response({"status": "failed"}, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
通常,ListCreateAPIView由GenericAPIView,ListModelMixin,CreateModelMixin混合,因此它不提供创建列表对象功能。它有趣〜listcreateapiview
这是一个例子,你应该用json格式数据发布它。
(load-pkcs12 #P"/path/to/sslcert.p12" "password")