简体   繁体   中英

How to add to cart in DRF

I am trying to create order:

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'),

I am confused here; should I create new order objects from serialzers or views?

You should override the created method on the AddtocartSerializers to add the order item to the order.

You can see more information about it here: https://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM