Search code examples
djangodatabase-designdjango-modelsdjango-adminmany-to-many

Django models deifinition many to many field


I have the following case:

class Product(models.Model):
    name = models.CharField(max_length=200)

class Order(models.Model):
    product = models.ManyToManyField(Product)
    quantity = models.IntegerField(default=0,validators=[MinValueValidator(1)])

and in admin.py

class ProductsInline(admin.TabularInline):
    model = Order.product.through

class OrderAdmin(admin.ModelAdmin):
    inlines = [ProductsInline,]
    filter_horizontal = ('product',)

I would like to enter a different quantity for each product while creating one order but with this models it is not possible. Only one quantity per order can be inserted.

I thought of creating an intermediate class ProductQuantity that has a product and its quantity, and then add this to an Order, but i don't know if it is possible to create a ProductQuantity "on the fly" when creating an order.

I can't think of any solution, can anyone help?


Solution

  • I am not sure if I get your questions. Would this solve your problem?

    class Product(models.Model):
        name = models.CharField(max_length=200)
    
    class Order(models.Model):
        customer = models.ForeignKey(Customer)
    
    class OrderItem(models.Model):
        order = models.ForeignKey(Order)
        product = models.ManyToManyField(ProductQuantity)
        quantity = models.IntegerField(default=0,validators=[MinValueValidator(1)])
    

    Edit:

    With the above Model you could create the following Orders:

    Products:
    +----+--------+
    | id |  name  |
    +----+--------+
    |  1 | apple  |
    |  2 | orange |
    |  3 | banana |
    +----+--------+
    
    Order:
    +----+-------------+
    | id | customer_id |
    +----+-------------+
    |  1 |         112 |
    |  2 |          99 |
    +----+-------------+
    
    OrderItem:
    +----+-------+---------+----------+
    | id | order | product | quantity |
    +----+-------+---------+----------+
    |  1 |     1 |       1 |       10 |
    |  2 |     1 |       2 |       20 |
    |  3 |     1 |       3 |       30 |
    |  4 |     2 |       1 |        5 |
    +----+-------+---------+----------+
    

    There are two orders from two different customers, one with 10 apples, 20 oranges and 30 bananas. And a second order with only one item of 5 apples.