Как добавить товар в корзину в django rest frame work drf

вот моя модель class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models. CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='cart_items') quantity = models.PositiveSmallIntegerField() class Meta: unique_together = [['cart', 'product']]

это мои взгляды

class CartItemViewSet(ModelViewSet): http_method_names = ['get','post','patch','delete'] serializer_class = CartItemSerializer queryset = CartItem.objects.all() def get_queryset(self): cart_pk = self. kwargs['cart_pk'] return CartItem.objects.select_related('product').filter(cart_id = cart_pk).all() def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request. method == 'PATCH': return ChangeCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_pk':self.kwargs['cart_pk']} class CartViewSet(CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet, ): serializer_class = CartSerializer queryset = Cart. objects.prefetch_related('items__product').all() lookup_value_regex = '[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?[0-9a-f]{12}'

и мой сериализатор

class

ProductSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=255, source='name') price = serializers.DecimalField(max_digits=6, decimal_places=2,source='unit_price') unit_price_after_tax = serializers. SerializerMethodField() class Meta: model = Product fields = ['id', 'title', 'price', 'category', 'unit_price_after_tax', 'inventory', 'description'] def create(self, validated_data): product = Product(**validated_data) product.slug = slugify(product.name) product.save() return product # def update(self, instance, validated_data): # instance.inventory = validated_data.get('inventory') # instance.save() # return instance def get_unit_price_after_tax(self , product): return round(product.unit_price * Decimal(1.09), 2) def validate(self, data): if len(data['name']) < 6: raise serializers.ValidationError('Product lentgh should be at least 6.') return data class CartProductSerializer(serializers. ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'unit_price'] class ChangeCartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['quantity'] class AddCartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['id', 'product', 'quantity'] def crea

может ли кто-нибудь помочь мне ???????????????????????????????

у меня есть

я пытаюсь искать в интернете и спрашивать в чате gpt но ничего не получается можете мне помочь

Вернуться на верх