Reputation: 2026
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:
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
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
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