'Define Django models for recipe

So, I need some help to design the models for my project. The project is quite simple, it is a cocktails maker. The idea is to have a model for all the ingredients (Vodka, coke, gin etc.), another model for the Cocktail and a last model with the recipe. How can I add some ingredients and choose their quantity into the Recipe model and then link the Recipe to the Cocktail model?

Here is what I have so far, the Ingredient model is working fine, but I'm struggling to design the Cocktail & Recipe model and choose their relationship.

class Ingredient(models.Model):


    name = models.CharField(null=False, blank=False, unique=True,
                        max_length=100, validators=[MinLengthValidator(3)])

    price = models.FloatField(null=False, blank=False)

    is_alcoholic = models.BooleanField(null=False, blank=False)


class Cocktail(models.Model):
    name = models.CharField(max_length=50)
    price = models.FloatField()
    description = models.TextField()
    recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE)


class Recipe(models.Model):
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.IntegerField()

Any suggestions are more than welcome!



Solution 1:[1]

Ok, so I think Cocktail and Ingredient would be a great place to use the ManyToManyField offered by Django instead of a regular ForeignKey. But you have to deal with quantity - as it changes from Cocktail to Cocktail. That is why you will need to use a custom “through” model. So Recipe is good for this, but you will have to add another ForeignKey field to your Recipe Model relating to the Cocktail it self. Hence you would have a Recipe Model that has many relations to a Cocktail and also many relations to Ingredients. But for one Cocktail it has n number relations, where n=number of ingredients. And quantity can be adjusted to - let's say - taste. :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sipi09