Reputation: 18
in a nutshell, i want to select multiple PRODUCT per one ORDER entry. should i use some string manipulation method to compose all selected product in one string and save it into single field ? it sounds obvious but i don't think its way to go because its like majority of database design confronts the order and its multiple products and there should be a better way to deal with it. please suggest a better practice or something magical like one can store multiple primary key in one foreign key field but seems like thats not the best practice somehow. so what should i do ?
Order_Product = models.ForeignKey(Product, on_delete=models.CASCADE)
# im thinking of making below field into a string holding container
# and join many primary key and just outright save it separating by commas
Order_SelectedProduct = models.CharField(max_length=1000)
Order_Amount = models.CharField(max_length=10)
Order_Qty = models.CharField(max_length=10)
Order_Date = models.CharField(max_length=10)
Order_Deadline = models.CharField(max_length=10)
Order_Reference = models.CharField(max_length=128)
def __str__(self):
return self.Order_Id
obviously that Order_SelectedProduct field is not ideal way because one primary takes 14 spaces so say one order can only be limited to store only 71 products per order, thats more than enough but thats not scalable. i hope it yields something fruitfull
Upvotes: 0
Views: 666
Reputation: 1810
What you need is many-to-many relationship.
For this you can define your models as:
models.py
class Product(models.Model):
....
def __str__(self):
return self.id
class Order(models.Model):
Order_Product = models.ManyToManyField(Product)
...
Then, to add multiple products in the order object, you can do something like:
order = Order() --> create a order object
order.Order_Product.add(product1)
order.Order_Product.add(product2)
# product1 and product2 are the product objects that were selected
# and so on
order.save()
For more clarification, you can refer to django many-to-many relationship
Upvotes: 2