ShellRox ShellRox - 1 year ago 108
Python Question

Django: How to properly make shopping cart? ( Array string field )

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.

class User(models.Model):
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.???

def __str__(self):
return self.username

How can I achieve having array string in models with using Django's system? If not then can it be possible by other libraries ( Json, Pickle ), but I've seen it can be done by ForeignKey, if so how is it possible?

Answer Source

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', ...)
diego = User.objects.get(username='dalleng')