0

I'm trying to create a data structure that involves Products, Customers and Orders. Customers and Products are independent tables, while the Orders references Products and Customers.

Orders table fields:

  1. Time stamp
  2. Customer
  3. Product along with Quantity

Here is my attempt at creating a django model to achieve this:

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=30)
    latitude = models.FloatField(default=0)
    longitude = models.FloatField(default=0)

class Product(models.Model):
    name = models.CharField(max_length=30)
    weight = models.FloatField(default=0)

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
    products = models.ManyToManyField(Product)
    quantity = ?

How do I create a quantity field that maps to a particular product? Alternate models to achieve the same results are also welcome.

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
NFern
  • 1,706
  • 17
  • 18
  • For those looking for how to use this model in django admin, this should help: https://stackoverflow.com/questions/6034047/one-to-many-inline-select-with-django-admin – NFern Aug 21 '17 at 03:36

2 Answers2

2

Use through in your ManyToManyField.

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=30)
    latitude = models.FloatField(default=0)
    longitude = models.FloatField(default=0)

class Product(models.Model):
    name = models.CharField(max_length=30)
    weight = models.FloatField(default=0)

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
    line_items = models.ManyToManyField(Product, through='OrderItem')

class OrderItem(models.Model):
    product = models.ForeignKey(Product)
    order = models.ForeignKey(Order)
    quantity, price, discount, ...
D.Nibon
  • 2,883
  • 1
  • 19
  • 17
0

I would suggest a model which contain a product and its quantity in an order. Something like below.

class ProductOrder(models.Model):
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()

Then in order:

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
    products = models.ManyToManyField(ProductOrder)
Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57