Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models - Quantity field

I'm using Django to create a part inventory where I work. Here is a snippet of the models I have:

class Part(models.Model):
    description = models.CharField(max_length=64)
    number= models.CharField(max_length=64)
    price= models.FloatField()

class Group(models.Model):
    name = models.CharField(max_length=64)
    parts = models.ManyToManyField(Part)

So I have different groups (orders) with some parts in it.

What I want to do is to have a quantity property for the parts of my group. But if I want to add the quantity field to my Part object, each group will have the same quantity, which is not the correct behavior. How can I have my groups remember how much of each part they have?

Thanks for your input and I hope this is not a total noob question!

like image 923
Speccy Avatar asked Dec 19 '12 16:12

Speccy


2 Answers

You would need a through table:

The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary.

class Part(models.Model):
    description = models.CharField(max_length=64)
    number= models.CharField(max_length=64)
    price= models.FloatField()

class Group(models.Model):
    name = models.CharField(max_length=64)
    parts = models.ManyToManyField(Part, through='GroupPart')
like image 154
karthikr Avatar answered Nov 15 '22 18:11

karthikr


Create a new through table between Group and Part that holds the quantity.

like image 4
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 19:11

Ignacio Vazquez-Abrams