问题描述
我正在将旧代码更新到最新的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
定义其他内容,可以尝试编辑此内联,例如使用:
You could try to use a regular expression here. Given the ForeignKey
s 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 ForeignKey
s can be replaced, but you can slightly alter the regular expression to accept different patterns.
请注意,您可能需要更新。
Note that you probably will need to update OneToOneField
fields [Django-doc] as well.
这篇关于如何自动更新外键使其具有“ on_delete = models.PROTECT”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!