Reputation: 57158
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.)
Upvotes: 1
Views: 2392
Reputation: 238
I don't recommend using ManyToMany field because prices needs to be saved as char field for future reference.
Make two models:
With: Order number, customer details, date created, payment details
2.OrderItem
With : Product, Price, Quantity, Discount, SKU
And use OrderItem as inline in Order model
Upvotes: 0
Reputation: 37671
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)
Upvotes: 7
Reputation: 863
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)
Upvotes: 0