Tim Clemans
Tim Clemans

Reputation: 63

How to automatically update ForeignKeys to have ", 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?

Upvotes: 1

Views: 169

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476803

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.

Upvotes: 4

Related Questions