如何在DRF中添加到购物车

时间:2019-12-20 11:01:16

标签: django python-3.x django-rest-framework

我正在尝试创建订单:

models.py

class OrderItem(models.Model):
      image_number = models.CharField(max_length=20)
      title = models.CharField(max_length=20)
      image_size = models.CharField(max_length=50)
      file_type = models.CharField(max_length=20)
      price = models.CharField(max_length=50)

      def __str__(self):
          return self.title

class Order(models.Model):
      user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
      items = models.ManyToManyField(OrderItem)
      start_date = models.DateTimeField(auto_now_add=True)
      ordered_date = models.DateTimeField()
      ordered = models.BooleanField(default=False)

      def __str__(self):
          return str(self.user)

serializers.py

 class AddtocartSerializers(serializers.ModelSerializer):
       class Meta:
             model = OrderItem
             fields = ['image_number','title','image_size','file_type','price']

class CartSerializers(serializers.ModelSerializer):
      class Meta:
            model = Order
            fields = ['item',
                'start_date',
               'ordered_date'
              ]

views.py

class AddtocartView(viewsets.ModelViewSet):
      authentication_classes = []
      permission_classes = []
      pagination_class = None
      queryset=OrderItem
      serializer_class = AddtocartSerializers

class CartView(viewsets.ModelViewSet):
      authentication_classes = []
      permission_classes = []
      pagination_class = None
      queryset=Order.objects.all()
      serializer_class = CartSerializers

urls.py :api endpint

 path('addtocart/',views.AddtocartView.as_view({'get':'list'}),name='addtocart'),
 path('cart/',views.CartView.as_view({'get':'list'}),name='cart'),

我在这里很困惑;我应该从序列化程序或视图中创建新的order对象吗?

1 个答案:

答案 0 :(得分:0)

您应该覆盖AddtocartSerializers上创建的方法,以将订单商品添加到订单中。

您可以在此处查看有关此信息的更多信息:https://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations