[英]Peewee Migration - Foreign key constraint?
I have searched and there are no questions here dealing with this. 我已经搜索过,这里没有问题可以解决。 I have some tables defined in my migrations like so -
我在迁移中定义了一些表,如下所示:
from playhouse.migrate import *
db = MySQLDatabase('mydb', 'root', 'password', 'localhost', 3306)
migrator = MySQLMigrator(db)
id_field = IntegerField(null=False, unique=True, index=True, primary_key=True)
fk_field = IntegerField(null=False)
with db.atomic():
migrate(
migrator.add_column('my_table', 'id', id_field)
)
with db.atomic():
migrate(
migrator.add_column('my_table1', 'id', id_field)
migrator.add_column('my_table1', 'table_id', fk_field) # this needs to be marked as a foreign key constraint somehow?
)
However, the documentation makes it very unclear how to specify in the migrations a foreign key constraint. 但是,文档非常不清楚如何在迁移中指定外键约束。 A ForeignKeyField seems to require a model which I do not have.
一个ForeignKeyField似乎需要一个我没有的模型。
Is there a way to specify in the migrations that table_id
is a foreign key that relates to the my_table
id field? 有没有一种方法可以在迁移中指定
table_id
是与my_table
id字段相关的外键? You would do this using FOREIGN KEY table_id REFERENCES my_table(id)
in standard SQL. 您可以在标准SQL中使用
FOREIGN KEY table_id REFERENCES my_table(id)
进行此操作。
Im at a loss and I'm about to dump my migrations for SQL because peewee's documentation doesn't really make this clear. 我不知所措,我将转储我的SQL迁移,因为peewee的文档并没有真正弄清楚这一点。 I am not using Django - I have just bolted on peewee to a few scripts I have.
我不使用Django-我只是在peewee上添加了我拥有的一些脚本。
What can I do to remedy this so migrations fully define my models? 我可以采取什么措施来解决此问题,以便迁移完全定义我的模型?
If you are trying to add a foreign-key to a model you do not "have", there are a couple ways. 如果您试图将外键添加到模型中,而您没有“拥有”,则有几种方法。 You could create a stub model to stand as a placeholder for the target of the foreign-key, and then call
add_column()
with a ForeignKeyField
. 您可以创建一个存根模型来充当外键目标的占位符,然后使用
ForeignKeyField
调用add_column()
。 Or you could specify a list of constraints explicitly in the IntegerField()
: 或者,您可以在
IntegerField()
显式指定约束列表:
field = IntegerField(..., constraints=[SQL('foreign key references foo(bar)')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.