[Answered ]-Django: How to properly make shopping cart? ( Array string field )

2👍

I’d suggest using DB relationships instead of storing a string or an array of strings for this problem.

If you solve the problem using DB relationships, you’ll need to use a ManyToManyField.

class User(models.Model):
    ...
    cart = models.ManyToManyField(Product)

And assuming you have a model for your products.

class Product(models.Model):
    name = models.CharField(max_length=30)
    price = models.DecimalField(max_digits=8, decimal_places=2)

When adding elements to the cart you’ll use something like this.

tv = Product(name='LED TV', ...)
tv.save()
diego = User.objects.get(username='dalleng')
diego.cart.add(some_product)

Leave a comment