1👍
✅
Your DetailOrder
acts as the through model of a ManyToManyField
. You can for the same Order
have multiple DetailedOrder
s, and thus also refer to multiple Product
s.
You can also span a ManyToManyField
[Django-doc] over this model to effectively find out the Product
s, with DetailedOrder
as the through=…
model [Django-doc]:
class Product(models.Model):
product_id = models.CharField(primary_key=True, max_length=100)
product_name = models.CharField(max_length=150)
class Order(models.Model):
order_id = models.CharField(primary_key=True, max_length=100)
customer_id = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
products = models.ManyToManyField(
Product,
through='DetailedOrder',
related_name='orders'
)
class DetailedOrder(models.Model):
order = models.ForeignKey(Order, null=True, on_delete= models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
quantity = models.IntegerField(default=1)
Note: Normally one does not add a suffix
…_id
to aForeignKey
field, since Django
will automatically add a "twin" field with an…_id
suffix. Therefore it should
beproduct
, instead of.product_id
Source:stackexchange.com