[英]How to change a value from in a django model while its foreign key?
Cart_Items , Cart , Order models .i want for my shopping website , that after a ordering a product , a value increased , but i cant access it . Cart_Items,Cart,Order模型。我要在我的购物网站上订购产品后,价值增加了,但我无法访问它。
i tried to get it by pr=Products.objects.all() ci=Cart_Items.filter(product_id=pr) 我试图通过pr = Products.objects.all()ci = Cart_Items.filter(product_id = pr)来获取它
my models.py: 我的models.py:
order model: 订单模型:
class Order(models.Model):
user = models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE)
order_id = models.CharField( max_length=120,default="ABC",unique=True)
cart = models.ForeignKey(Cart,on_delete=models.CASCADE)
statu = models.CharField(max_length=120,choices=STATUS_CHOICES,default="Started")
product model: 产品型号:
class Products(models.Model):
title = models.CharField(max_length=250)
order_qty = models.IntegerField(default=0)
Cart_Items model: Cart_Items模型:
class Cart_Items(models.Model):
cart = models.ForeignKey('Cart',null=True,blank=True,on_delete=models.CASCADE)
product_id = models.ForeignKey(Products,null=True,blank=True,on_delete=models.CASCADE)
cart model : 推车型号:
class Cart(models.Model):
total = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
date = models.DateTimeField(auto_now_add=False,auto_now=True)
isPaid = models.BooleanField(default=False)
my views.py: 我的views.py:
def add(request):
cart_items=Cart_Items.objects.all()
for item in cart_items:
print(item.product_id.order_qty)
item.product_id.order_qty +=1
render(request,"home.html",{})
i want after ordering a product , order_qty , increased , how can i do that ? 我要订购的产品order_qty增加后,该怎么办? i must do it by Cart_items ?
我必须由Cart_items完成吗? or there is another ways ?
还是还有另一种方法? plz help.
请帮助。
You have to call save method, after you change a value: 更改值后,必须调用save方法:
def add(request):
cart_items=Cart_Items.objects.all()
for item in cart_items:
print(item.product_id.order_qty)
item.product_id.order_qty +=1
item.save()
render(request,"home.html",{})
Or like @Wilem said, you can count the quantity by the number of all the items in the order: 或就像@Wilem所说的那样,您可以通过订单中所有项目的数量来计算数量:
Order.objects.all().count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.