如何添加到购物车drf

时间:2019-12-24 08:08:15

标签: 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(generics.CreateAPIView):
      authentication_classes = []
      permission_classes = []
      pagination_class = None
      queryset=OrderItem.objects.all()
      serializer_class = AddtocartSerializers


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

      def create(self, request):        
          return super(AddtocartView, self).create(request, *args, **kwargs)

urls.py:

path('addtocart/',views.AddtocartView.as_view(),name='addtocart'),
path('cart/',views.CartView.as_view(),name='cart'),

在添加购物车后如何创建订单?

2 个答案:

答案 0 :(得分:0)

我首先建议您不要使用ModelViewSet,因为您所需的只是为视图创建和更新,创建时使用CreateAPIView,更新时使用RetrieveAPIView。 您的代码将如下所示:

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

class OrderCreateSerializer(serializers.ModelSerializer)
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    items = serializers.ListField(child=serializers.PrimaryKeyRelatedField(queryset=OrderItem.objects.all(), required=True), required=True)
    ordered_date = serializers.DateField()

    class Meta:
        model = Order
        fields = ['user', 'items', 'ordered_date']

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user 
        instance = Order.objects.create(**validated_data)
        instance.save()
        return instance


class CartView(CreateAPIView):
      authentication_classes = []
      queryset=Order.objects.all()
      serializer_class = OrderCreateSerializer

      def create(self, request):
          return super(AddtocartView, self).create(request, *args, **kwargs)

ModelViewSet包含更多您不使用的代码。而且您还可以从请求中获取用户,只需添加

validated_data['user'] = self.context['request'].user

答案 1 :(得分:0)

是的,您可以向addtocart端点发出发布请求。但是必须在addtocart端点中编写逻辑以创建订单并将OrderItem添加到订单。然后必须将订单号返回到浏览器,以便用户可以继续购物/结帐。

收到订单号后,您可以执行一些JavaScript程序,向用户显示其订单详细信息。