简体   繁体   English

Django 如何使用多对多关系?

[英]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 .正如 Neeraj 所说,您需要ManyToManyField而不是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 . ForeignKey用于多对一的关系——例如,一个作者可能有很多本书,但如果每本书只有一个作者,那么这将是一个多对一的关系,所以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).然而,如果每本书也有很多作者,那么这将是一个多对多的关系(一本书有很多作者,一个作者有很多书)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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