Lately I've been needing to create a server-side shopping cart for my website that can have products inside. I could add cart and product in session cookies, but I prefer to add it to my custom made User model, so it can stay when the user decides to log out and log back in.
Since I'm making a shopping cart, I need to make a model for it, that will hold products as objects, so then they can be easily used, but I can't find any way to do so properly.
username = models.CharField(max_length=150)
joined = models.DateTimeField('registered')
avatar = models.CharField(max_length=300)
balance = models.IntegerField(default=0)
ban = models.BooleanField()
cart = models.???
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)