Search code examples
djangodjango-modelsdjango-inheritance

django inheritance hurts my brain


I'm making a beer website, and I'm stuck. I need to have a recipe that i can relate to many different ingredients. Is there a way to create a model "Ingredient", and inherit many different models: "Hop", "Grain", etc. I would want to do this so I have my relationship between recipe and ingredient, and i don't have to create 100 different relationships to cover each kind of ingredient.

Is this possible?


Solution

  • Although I would personally advise against it in most cases since table inheritance is a pain (imho) in Django.

    You can do it like this:

    class Recipe(models.Model):
        name = models.CharField()
    
    class Ingredient(models.Model):
        name = models.CharField()
        recipes = models.ManyToManyField(Recipe, related_name='%(app_label)s_%(class)s')
    
    class Hop(Ingredient):
        pass
    
    class Grain(Ingredient):
        pass