如何自动更新外键使其具有“ on_delete = models.PROTECT”; [英] How to automatically update ForeignKeys to have ", on_delete=models.PROTECT"

查看:524
本文介绍了如何自动更新外键使其具有“ on_delete = models.PROTECT”;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将旧代码更新到最新的Django版本。

ForeignKeys需要, on_delete = models.PROTECT

其中几乎有一百个。如何自动为每个人添加 on_delete = models.PROTECT?

I'm updating old code to the latest Django version.
The ForeignKeys need ", on_delete=models.PROTECT".
There are almost a hundred of them. How do I automatically add ", on_delete=models.PROTECT" to each one?

推荐答案

您可以尝试使用正则表达式这里。鉴于 ForeignKey 是在单行上定义的,并且您没有使用 ForeignKey 定义其他内容,可以尝试编辑此内联,例如使用 sed [wiki]

You could try to use a regular expression here. Given the ForeignKeys are defined on a single line, and you did not define something else with ForeignKey, you could try to edit this inline, for example with sed [wiki]:

sed -i -E 's/(ForeignKey\s*\(.*)\)\s*$/\1, on_delete=models.PROTECT)/' */models.py

因此,我们在这里将内联替换目录中的所有 models.py ,其中 ForeignKey(…) ForeignKey(… ,on_delete = models.CASCADE

We here will thus do an inline replacement of all the models.py in a directory, where we replace ForeignKey(…) with ForeignKey(…, on_delete=models.CASCADE).

也许不是所有的 ForeignKey 都可以替换,但是您可以稍微修改正则表达式以接受不同的模式。

Perhaps not all ForeignKeys can be replaced, but you can slightly alter the regular expression to accept different patterns.

请注意,您可能需要更新 OneToOneField 字段也是[Django-doc]

Note that you probably will need to update OneToOneField fields [Django-doc] as well.

这篇关于如何自动更新外键使其具有“ on_delete = models.PROTECT”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆