Question

I'm trying to represent a mixture in Django. Something like:

Chemical #1 - 50%
Chemical #2 - 30%
Chemical #3 - 20%

I figured I would use a wrapper called composition as follows:

class Composition(models.Model):
    """ Just a Wrapper """
    def save(...):
        #Validate ingredients add up to 100% and such


class Ingredient(models.Model):
    composition = models.ForeignKey('Composition',related_name='ingredients')
    name = models.CharField(max_length = 10)
    percentage = models.IntegerField()

I'm pretty sure there's a better way to do this. Keep in mind that I'm doing it like this so I can later use inlines in the Django admin. What do you guys recommend? Thanks a lot =)

Was it helpful?

Solution

It seems to me as though it would be preferable to keep a list of ingredients then reference those when you create your compositions, rather than entering the ingredient names each time. You could do it using a many to many relationship and a through table, like so:

class Ingredient(models.Model):
    name = models.CharField(max_length=10)

class Composition(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient, through='CompositionIngredient')

    def save(...):
        #Validate ingredients add up to 100% and such

class CompositionIngredient(models.Model):
    composition = models.ForeignKey(Composition)
    ingredient = models.ForeignKey(Ingredient)
    proportion = models.DecimalField()

See the Django docs for more information.

EDIT: Here's the documentation on how to deal with through tables in the admin interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top