Skip to content
Advertisement

Trying to add a field to Django many-to-many relation

Right now I’m working on a Django project responsible for the warehouse management system. I got products, customers, warehouse branches, product types, orders, etc… products can be [Milk 1L bottle, cheese 500g pack, ….] The problem I have been facing is that I’m trying to make a many-to-many relationship between orders and products so I can track the products sold in each order. Yet, I want to add the ‘quantity’ column to that table created by many-to-many because a customer can order 5 cheese packs and 2 milk bottles. I know that I can add ‘ManyToManyField.through’ but it takes a string for a model as args and that’s what I don’t want.

I wish to easily have an extra IntegerField called quantity.

Here’s how I wish my table to look-like

enter image description here

Advertisement

Answer

I suggest you use these models:

class Product(models.Model):
    title = ...


class Order(models.Model):
    user = ...
    address = ...

class OrderItem(models.Model):
    order = models.ForeignKey(Order,...)
    product = models.ForeignKey(Product,...)
    quantity= ...

Now your customers can have many order items with products in each order.

Advertisement