簡體   English   中英

如何將數據添加到其列被 Django 中的其他模型引用(外域)的模型中

[英]How to add data to the model whose column are referenced(Foreign Field) from other model in Django

我正在嘗試將數據添加到我的購物車模型,但收到錯誤,因為在我嘗試輸入數據的字段中是 ForeignField,其引用為 Items。
無法分配“9”:“Cart.pid”必須是“items”實例。

這是我的代碼:-

視圖.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')

模型.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)

請幫忙!!!

當我們在 Django 中使用外鍵時,可以使用相關的對象實例或數據庫字段的原始值。 在您的代碼中,您有一個名為pid的字段。 您可以為其分配一個對象實例:

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)

...或者將鍵值 ( 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM