Reputation: 3954
I have an order of a certain list of products, and I need to model this in Django.
Each order has properties:
id
email
total_price
line_items
line_items is a dictionary of products and the number of instances of that product required.
Product is a separate model describing a class of products.
I need a many-to-many relationship between Product and Order because each product could be part of many orders, but each order could have many products - how does this look in my fields given that I could have an order that has 3 instances of one product, 2 of another etc...?
Upvotes: 2
Views: 6423
Reputation: 477190
line_items
is a dictionary of products and the number of instances of that product required.
I would suggest not to store this in a dictionary. In a relational database, one typically stores this in a different table over multiple records. The advantage of this, is that it is easy to query. For example to generate a list of all orders that contain a certain product, or contain a certain product with a quantity higher than 50.
We thus typically have three tables:
+-------+ 1 N +--------------+ N 1 +---------+
| Order |----------| OrderProduct |----------| Product |
+-------+ +--------------+ +---------+
| email | | quantity |
+-------+ +--------------+
We thus have three models: Order
, OrderProduct
and Product
, for example:
Order(models.Model):
email = models.EmailField()
Product(models.Model):
# ...
pass
OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
class Meta:
unique_together = ('order', 'product')
We thus can construct an order like:
product1 = Product.objects.create()
product2 = Product.objects.create()
my_order = Order.objects.create(email='[email protected]')
OrderProduct.objects.create(product=product1, order=my_order)
OrderProduct.objects.create(product=product2, order=my_order, quantity=14)
So here we constructed two products and one order, and we added two OrderProduct
s to this order, one for product1
, and one for product2
with a quantity of 14
.
Upvotes: 11