简体   繁体   中英

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.
Cannot assign "9": "Cart.pid" must be a "items" instance.

Here is my code:-

Views.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

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. In your code, you have a field named 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM