Python Django指向现有关系表的点ForeignKey
我对Django相当陌生,我想实现以下目标:我在两个表之间有一个关系,比如说表B有很多对表a的引用。现在我想要一个名为Options的表,它将选项保存到a和B之间的特定组合中。我如何实现这一点 谢谢 Hidde使用Python Django指向现有关系表的点ForeignKey,python,django,foreign-key-relationship,Python,Django,Foreign Key Relationship,我对Django相当陌生,我想实现以下目标:我在两个表之间有一个关系,比如说表B有很多对表a的引用。现在我想要一个名为Options的表,它将选项保存到a和B之间的特定组合中。我如何实现这一点 谢谢 Hidde使用ManyToMany字段的选项,并在关系本身中添加信息 比如说 class Ingredient(models.Model): name = models.TextField() class Recipe(models.Model): name = models.Te
ManyToMany
字段的选项,并在关系本身中添加信息
比如说
class Ingredient(models.Model):
name = models.TextField()
class Recipe(models.Model):
name = models.TextField()
ingredients = models.ManyToManyField(Ingredient, through='RecipePart')
class RecipePart(models.Model)
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
amount = models.IntegerField()
# ...
RecipePart(recipe=pizza, ingredient=cheese, amount=9001).save()
如果关系已经存在(并且您已经有数据),则必须更新数据库架构(如果您习惯于自动映射,则必须创建模型)。可以帮助您完成此操作。使用ManyToMany
字段的选项,并在关系本身中添加信息
比如说
class Ingredient(models.Model):
name = models.TextField()
class Recipe(models.Model):
name = models.TextField()
ingredients = models.ManyToManyField(Ingredient, through='RecipePart')
class RecipePart(models.Model)
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
amount = models.IntegerField()
# ...
RecipePart(recipe=pizza, ingredient=cheese, amount=9001).save()
如果关系已经存在(并且您已经有数据),则必须更新数据库架构(如果您习惯于自动映射,则必须创建模型)。我可以帮你做这件事。谢谢你的快速回复!谢谢你的快速回复!