Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
How to associate quantity amount in Django's many to many relationship

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Define an intermediary 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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!