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

Question:

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)

Answers:

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

order_object = Order(
    user=request.user, variation=variation_obj, quantity=quantity, total=total
)
Answered By: Willem Van Onsem
order_object = Order(
    user=request.user, 
    variation=variation_obj, 
    quantity=quantity, 
    total=total
).save()

Pass the foreinkey object instead of it’s id

Answered By: ANFAS PV