[英]How to add data to the model whose column are referenced(Foreign Field) from other model in Django
I am trying to add data to my Cart Model but getting the error as In the field in which I am trying to enter the data is the ForeignField whose reference is Items.我正在尝试将数据添加到我的购物车模型,但收到错误,因为在我尝试输入数据的字段中是 ForeignField,其引用为 Items。
Cannot assign "9": "Cart.pid" must be a "items" instance.无法分配“9”:“Cart.pid”必须是“items”实例。
Here is my code:-这是我的代码:-
Views.py视图.py
def add_cart(request):
pid = request.POST.get('cart_id')
quantity = request.POST.get('quantity')
details = items.objects.filter(pk = request.POST.get('cart_id'))
name = None
price = None
for i in details:
name = i.name
price = i.price
pid = i.id
user_id = request.user.id
total = int(quantity)*price
instance = Cart(pid = pid,quantity = quantity,pro_name = name,pro_price = price,user_id = user_id,total = total)
return redirect('home')
Models.py模型.py
class items(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100,default='Item')
desc = models.TextField(max_length=500, default='Best')
price = models.IntegerField()
category = models.CharField(max_length=50,default='Product')
image = models.ImageField(upload_to="media",default='Item Image')
class Cart(models.Model):
pid = models.ForeignKey('items',on_delete=CASCADE,related_name="proid")
name = models.ForeignKey('items',on_delete=CASCADE,related_name="proname")
price = models.ForeignKey('items',on_delete=CASCADE,related_name="proprice")
quantity = models.IntegerField(default=1)
user_id = models.ForeignKey(User,on_delete=CASCADE)
total = models.IntegerField(default=0)
Please help!!!请帮忙!!!
When we use a Foreign Key in Django, can use the related object instance or the database field raw value.当我们在 Django 中使用外键时,可以使用相关的对象实例或数据库字段的原始值。 In your code, you have a field named pid
.在您的代码中,您有一个名为pid
的字段。 You can assign a object instance to it:您可以为其分配一个对象实例:
for i in details:
name = i.name
price = i.price
pid = i # <!-- no i.id, i is the object instance
user_id = request.user.id
total = int(quantity)*price
instance = Cart(pid = pid,quantity = quantity,pro_name = name,pro_price = price,user_id = user_id,total = total)
...Or assign the key value ( i.id
) to the magically created property pid_id
: ...或者将键值 ( i.id
) 分配给神奇地创建的属性pid_id
:
for i in details:
name = i.name
price = i.price
pid = i.id
user_id = request.user.id
total = int(quantity)*price
instance = Cart(pid_id = pid,quantity = quantity,pro_name = name,pro_price = price,user_id = user_id,total = total)
# We are ising the raw database value. W read it from `i.id` above.
instance.pid_id = pid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.