DMT
DMT

Reputation: 57

How can a second model reference a user instance that is a foreign key in the first model

I have a product model that includes a user(the user that adds the product)

class PreOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
contact = models.CharField(max_length=15)
product = models.CharField(max_length=50)
quantity = models.IntegerField()
unit_of_measurement = models.CharField(max_length=20, blank=True, null=True)
expected_time = models.DateField()

def __str__(self):
    return self.product

and cartItem model that references the product model (product field) and the owner of the product (product_owner field). The product_owner field is to keep tract of the owner of the product so that whenever an order is placed, I will know the owner whose products are being bought.

class CartItem(models.Model):
cart = models.ForeignKey('Cart',null=True, blank =True,on_delete=models.CASCADE)
product = models.ForeignKey(Product,related_name="product", on_delete=models.CASCADE)
quantity=models.IntegerField(default=1)
product_owner=models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE,blank=True,null=True)
line_total=models.DecimalField(max_digits=10, decimal_places=2, default=0.00)


def __str__(self):
    try:
        return str(self.cart.id)
    except:
        return self.product.title

in the view.py I tried adding the owner of product as in the case below

if request.method == "POST":
    qty = request.POST['qty']
    product= Product.objects.get(slug=slug)

    cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)

    cart_item.quantity = qty

    cart_item.product_owner = product.user
    cart_item.save()

when i submit locally, the owner gets added to the cartItem, but on the server, it throws an error: django.db.utils.ProgrammingError: column cart_cartitem.product_owner_id does not exist LINE 1: ...rtitem"."product_id", "cart_cartitem"."quantity", "cart_cart...

what is the best way to add the product owner to the cartItem? Thank you.

Upvotes: 0

Views: 55

Answers (1)

Kareem
Kareem

Reputation: 609

The error is simply saying that the column it's trying to save data to does not exists.

django.db.utils.ProgrammingError: column cart_cartitem.product_owner_id does not exist LINE 1: ...rtitem"."product_id", "cart_cartitem"."quantity", "cart_cart...

Simply run in your terminal and try again.

python manage.py makemigrations
python manage.py migirate

Upvotes: 1

Related Questions