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.

1

2 Answers 2

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, ...
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Thank you, this was in the correct direction. What worked for me is the "through ="

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.