Created
July 10, 2018 20:05
-
-
Save dcwatson/9a9dc4de4622e3fce3b948efa51b63ed to your computer and use it in GitHub Desktop.
Add on_delete to Django models for upgrading to 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
fk = re.compile(r'\s*([^\s]+)\s*=\s*models\.?(ForeignKey|OneToOneField)\(([^\s,\)]+)') | |
def fix(path, line): | |
line = line.rstrip() | |
# Weed out non-FKs, FKs with on_delete, or incomplete lines (will need to be done manually) | |
if ('ForeignKey' not in line and 'OneToOneField' not in line) or 'on_delete' in line or not line.endswith(')'): | |
return line | |
if fk.match(line): | |
if 'null=True' in line: | |
line = line[:-1] + ', on_delete=models.SET_NULL)' | |
else: | |
line = line[:-1] + ', on_delete=models.CASCADE)' | |
print(path, line) | |
return line | |
if __name__ == '__main__': | |
for root, dirs, files in os.walk('.'): | |
for name in files: | |
if name == 'models.py': | |
lines = [] | |
path = os.path.join(root, name) | |
with open(path, 'r') as f: | |
for line in f: | |
lines.append(fix(path, line)) | |
with open(path, 'w') as f: | |
f.write('\n'.join(lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment