How to automatically update ForeignKeys to have “, on_delete=models.PROTECT”

后端 未结 1 375
悲&欢浪女
悲&欢浪女 2021-01-24 23:33

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 autom

相关标签:
1条回答
  • 2021-01-24 23:54

    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

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

    Perhaps not all ForeignKeys 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.

    0 讨论(0)
提交回复
热议问题