In Django I have 2 models. One called Box and one called Product. A Box can have many different products and with different quantities of each product. For example box1 can have 1 productA and 2 productB.
My box model
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product = models.ManyToManyField(Product)
def __str__(self):
return self.boxName
My product model
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName
How do I set up this model allowing me to select quantity of a products when creating the box object?
CodePudding user response:
Define a new model that contains product quantity.
class Box(models.Model):
boxName = models.CharField(max_length=255, blank = False)
product_set = models.ManyToManyField(ProductSet)
def __str__(self):
return self.boxName
class ProductSet(models.Model):
quantity = models.PositiveIntegerField()
product = models.ForeignKey(Product, on_delete = models.PROTECT)
class Product(models.Model):
productName = models.CharField(max_length=200)
productDescription = models.TextField(blank=True)
productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0)
class Meta:
db_table = 'products'
ordering = ['-productName']
def __str__(self):
return self.productName