Home > Software design >  Django raise ValueError( ValueError: Cannot assign "1": "Order.variation" must b
Django raise ValueError( ValueError: Cannot assign "1": "Order.variation" must b

Time:09-30

Im trying to create a Orderobject but I get this error, and I dont know how to fix

   variation_obj = ProductVariation.objects.get(id=int(variation_id_list[index]))
                 quantity = variation_quantity_list[index]
                 total = variation_total_list[index]
                 total = float(total)
                 order_object = Order(user=request.user, variation=variation_obj.id, quantity=quantity, total=total)

error:

 Django   raise ValueError( ValueError: Cannot assign "1": "Order.variation" must be a "ProductVariation" instance.

models.py

class Order(models.Model):

    variation = models.ForeignKey(ProductVariation,
                                  on_delete=models.DO_NOTHING)
    created_at = models.DateField(auto_now_add=True)
    uploaded_at = models.DateField(auto_now=True)
    quantity = models.IntegerField()
    total = models.FloatField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

CodePudding user response:

order_object = Order(
    user=request.user, 
    variation=variation_obj, 
    quantity=quantity, 
    total=total
).save()

Pass the foreinkey object instead of it's id

CodePudding user response:

For the variation, you use the variation_obj object, so:

order_object = Order(
    user=request.user, variation=variation_obj, quantity=quantity, total=total
)
  • Related