NFern
NFern

Reputation: 2026

Django Many-to-Many data model

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.

Upvotes: 0

Views: 290

Answers (2)

D.Nibon
D.Nibon

Reputation: 2919

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, ...

Upvotes: 2

Arpit Solanki
Arpit Solanki

Reputation: 9931

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)

Upvotes: 0

Related Questions