Django: How to properly make shopping cart? ( Array string field )
<p>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.</p>

<p>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.</p>

<pre><code>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
</code></pre>

<p>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?</p>

<p>I'd suggest using DB relationships instead of storing a string or an array of strings for this problem.</p>

<p>If you solve the problem using DB relationships, you'll need to use a <a href="https://docs.djangoproject.com/es/1.10/topics/db/examples/many_to_many/" rel="nofollow">ManyToManyField</a>.</p>

<pre><code>class User(models.Model):
    ...
    cart = models.ManyToManyField(Product)
</code></pre>

<p>And assuming you have a model for your products.</p>

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

<p>When adding elements to the cart you'll use something like this.</p>

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

python django