繁体   English   中英

Django将ForeignKey指向现有关系表

[英]Django point ForeignKey to an existing relationship table

我是Django的新手,我想要实现以下目标:我在两个表之间有一个关系,例如表B对表A有一个ManyToMany引用。现在我想要一个名为Options的表,该选项将选项保存到A和之间的特定组合B.如何做到这一点?

谢谢!

隐藏的

使用ManyToMany字段的through选项,然后在关系本身中添加信息。

例如

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()

如果关系已经存在(并且您已经有数据),则必须更新数据库架构(如果您曾经使用自动映射,则必须创建模型)。 南方可以帮助您做到这一点。

暂无
暂无

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

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