I re-read Django’s documentation and can’t solve the problem.

For example, there are two models Cart and Products :

 class Cart(models.Model): cartnumber = models.CharField() products = models.ManyToManyField(Products) total = DecimalField() class Products(models.Model): name = CharField() price = DecimalField() 

Everything communicates well, everything is fine in the admin area too, but the task is different. As I understand it, a ManyToMany creates an intermediate table with the id of the Cart and Products tables. But I need that in this intermediate table there were more fields, for example the volume of the product ordered, its amount. I do not understand how to organize this business. Maybe I misunderstand the point? Tell me good people, how can I properly organize the work of a basket with several goods?

    1 answer 1

    The correct solution is to change the logic of working with the basket and completely abandon the Cart model and many-to-many relationships.

     class Purchase(models.Model): customer = models.ForeignKey(User, related_name='basket') product = models.ForeignKey(Product, related_name='+') count = models.PositiveSmallIntegerField() @property def cost(self): return self.product.price * self.count 

    But you can do it with an intermediate model.

     class Cart(models.Model): cartnumber = models.CharField() products = models.ManyToManyField(Products, through='Purchase') total = DecimalField() class Purchase(models.Model): cart = models.ForeignKey(Cart) product = models.ForeignKey(Product) count = models.PositiveSmallIntegerField() cost = DecimalField() 
    • In the first variant, it turns out that each product from the basket will have its own entry in the Purchase table? In my case, it is necessary that there are several products referring to one table. I tried the second case, maybe I am doing something wrong, but as soon as I add through = 'Purchase', the field disappears from the admin panel. - Alexander Kochetkov
    • In the first case, without problems, the user buys ten products, 10 copies of the Purchase . In the second, you'll have to use inlines to display an intermediate table . - Sergey Gornostaev