How to create Model with nested object in Django

Viewed 228

I'm trying to create a small product manufacturing app with Django. There are two main models in the app.

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

class ProductionOrder(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    entries = # not sure what goes here

I would like ProductionOrder.entries to be a list of dictionaries which include the Product and a quantity value.

The created ProductionOrder would appear as so (not exactly sure :

productionOrder = {
   'id': 2, 
   'entries': [
      { 'product': 'product_1_ref', 'quantity': 10},
      { 'product': 'product_2_ref', 'quantity': 10}
   ]
}

How can I accomplish this in a correct way?

1 Answers

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)
])
Related