[Answered ]-Does this many-to-many relationship make sense?

1👍

Your DetailOrder acts as the through model of a ManyToManyField. You can for the same Order have multiple DetailedOrders, and thus also refer to multiple Products.

You can also span a ManyToManyField [Django-doc] over this model to effectively find out the Products, 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 a ForeignKey field, since Django
will automatically add a "twin" field with an …_id suffix. Therefore it should
be product, instead of product_id.

Leave a comment