简体   繁体   中英

Django how to use a ManyToMany-Relationship?

I need an OneToMany-Relationship because I want to store Recipes. To do that I have two Models one is the Recipe and the other is the ingredient. When googling for this topic I always found using a foreign-key but I am not sure if its that what I am looking for. I wanted to test it but I found nowhere how to use this relationship.

The Models:

class Ingredient(models.Model):
    ingredient_title = models.CharField(max_length=120)
    amount = models.IntegerField()
    unit = models.CharField(max_length= 10)

class Recipe(models.Model):
    title = models.CharField(max_length=120)
    ingredients = models.ForeignKey(Ingredient,on_delete=models.CASCADE) `#Here I am not sure if its right`
    preperation = models.TextField(default='Here comes the preperation...')

I tried creating a recipe model but on the admin page I could select just one ingredient and in the shell, I didn't know how to do that.

Here is what I tried:

Recipe.objects.create(title='Essen1',ingredients=[(ingredient_title="ZutatTitel1",amount=2,unit='g'),(ingredient_title="ZutatTitel1",amount=2,unit='g')],preperation='prep1'))

you need to use ManytoMany Field. A recipe can have many ingredients.

class Recipe(models.Model):
title = models.CharField(max_length=120)
ingredients = models.ManyToManyField(Ingredient) 
preperation = models.TextField(default='Here comes the preperation...')

recipe_obj = Recipe.objects.create(title='Essen1)
recipe_obj.ingredients.add(ingredient_obj1)
recipe_obj.ingredients.add(ingredient_obj2)

As Neeraj said you need ManyToManyField instead of ForeignKey . This is because one ingredient can have (or belong to) many recipes and one recipe can have many ingredients. ForeignKey is used for many-to-one relationships - for example, one author might have many books but if each book has only one author then it would be a many-to-one relationship so ForeignKey . If however each book also had many authors then it would be a many-to-many relationship (one book has many authors and one author has many books).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM