我想在我的模型中使用django REST框架添加多個對象。用戶將把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)
請確保您的問題清晰明確。寫購物車有點太模糊。 – Linovia
抱歉,延遲。我做了一些改變@Linovia –
你的實際問題是什麼? – Bono