views:

166

answers:

2

I don't know if I'm thinking of this the right way, and perhaps somebody will set me straight.

Let's say I have a models.py that contains this:

class Order(models.Model):
  customer = models.foreignKey(Customer)
  total = models.charField(max_length=10)
  has_shipped = models.booleanField()

class Product(models.Model):
  sku = models.charField(max_length=30)
  price = models.charField(max_length=10)

Now, obviously an order would contain products and not just a product. What would be the best way to add products to an order? The only way I can think is to add another field to 'Order' called 'products', and fill it with a CSV with a sku for each product in it. This, for obvious reasons is not ideal, but I'm not very good at this stuff yet and have no idea of what the better way is.

(keep in mind this is pseudo code, so don't mind misspellings, etc.)

A: 

You can create one more model which will serve as many-to-many relationship between Order and Products

something like this

class OrderProducts(models.Model)
     product = models.ForeignKey(Product)
     order = models.ForeignKey(Order)
tdelev
This is redundant as the Order itself already serves as the "Order of Products"
drozzy
Yes, but in the answer.At the time that i wrote this answer I just didn't remember of the type models.ManyToManyField in django so proposed classical solution.
tdelev
This is not redundant. What if you have a price change in the future. If you had a price change, and the order was only linked to the original products, you would have no way of knowing how much the customer paid for what. This way you can mirror the products in their current state at the time of the order.
orokusaki
+7  A: 

What you're after is a many to many relationship between product and order.

Something like:

class Order(models.Model):
  customer = models.foreignKey(Customer)
  total = models.charField(max_length=10)
  has_shipped = models.booleanField()
  products = models.ManyToManyField(Product)

see the docs here and here.

Gareth Simpson
This. Might want to format your URLs.
drozzy
Is that better?
Gareth Simpson
Thanks man. I was just reading "Python Web Development with Django" today and came to that conclusion, but have been trying to figure out all day if it was correct. Thank you.
orokusaki