如何在django中正确保存表行值

时间:2016-11-24 09:38:36

标签: jquery python django

我有两个django模型用于订单和订单商品。我循环遍历jquery中的每个表行,并通过ajax将结果传递给View。问题是,对于每个被触发的ajax调用,它都会创建一个数据库记录。 orders.I想从表行创建订单和相应的订单商品。我做错了什么。谢谢

//视图

class ProductListView(TemplateView):
    def post(self,request,*args,**kwargs):
        if request.is_ajax():
            line_items = {}
            product_id = request.POST.get("product_id")
            price = request.POST.get("price")
            quantity = request.POST.get("quantity")
            subtotal = request.POST.get("subtotal")
            grandtotal = request.POST.get("grandtotal")
            products = CustomerPrice.objects.get(id=product_id)
            product_name = products.product

            line_items = {
              "product_id":product_name,
              "price":price,
              "quantity":quantity,
              "subtotal":subtotal,
              "grandtotal":grandtotal,
            }


        Order.objects.place('Credit Card','Pending',
                grandtotal,subtotal,125,line_items,request.user)
       return super(ProductListView,self).get(request)

//模型经理

class OrderManager(models.Manager):
    def place(self,payment_method,payment_status,
              grandtotal,sub_total,po_number,lineitems,username):

        charge_amount = float(lineitems['grandtotal'])
        order = self.create(customer=username,
                            sub_total=lineitems['subtotal'],
                            total = lineitems['grandtotal'],
                            charge_amount=charge_amount,
                            #payment_method=payment_method,
                            payment_status=payment_status,
                            order_number=po_number)
                            #billing_address=billing_address,
                            #updated_by=username,
                            #created_by=username)

        OrderItem.objects.create(order=order,
                                 product=lineitems['product_id'],
                                 price=lineitems['price'],
                                 quantity=lineitems['quantity'],
                                 sub_total=lineitems['subtotal'],
                                 total =lineitems['subtotal'],
                                 #tax_rate=tax_rate,
                                 #tax_method=tax_method,
                                 updated_by=username,
                                 created_by=username)

        return order

1 个答案:

答案 0 :(得分:0)

我会告诉你应该如何实施。使用有效负载制作单个ajax post请求。

{customer: "", payment_method: "" ... line_items: [ { product_id: '101', quantity: '2', ... }, { product_id: '102', quantity: '1', ... }] }

现在在django视图中,使用Ordercustomer详细信息等创建payment_method对象,并遍历每个订单项并创建相应的OrderLineItem对象。< / p>