[Django]-How to create Model with nested object in Django

3👍

You use a model in the middle that refers to the ProductionOrder and the Product, and you can span a ManyToManyField [Django-doc] to make filtering more elegant:

class Product(models.Model):
    name = models.CharField(max_length=100, blank=True, default='')

class ProductionOrder(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    products = models.ManyToManyField(
        Product,
        through='ProductOrder',
        related_name='orders'
    )

class ProductOrder(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    order = models.ForeignKey(ProductionOrder, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

If you thus have two products p1 and p2, and you want to add five items of p1 and seven items of p2 to an order o1, we can work with:

p1 = … # first product
p2 = … # second product
o1 = … # first order

ProductOrder.objects.bulk_create([
    ProductOrder(product=p1, order=o1, quantity=5),
    ProductOrder(product=p1, order=o1, quantity=7)
])

Leave a comment