inspectdb fixer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import fileinput
import re
import sys

active_model = ""

for line in fileinput.input():
    if active_model == "" and not line.startswith("class"):
        sys.stdout.write(line)
        continue
    if line.startswith("#"):
        sys.stdout.write(line)
        continue
    if line.startswith("class"):
        active_model = re.findall("class\ (.*)\(models.Model\):", line)[0]
        sys.stdout.write(line)
        continue
    if "models.ForeignKey" in line:
        line = re.sub("ForeignKey\((.*),", "ForeignKey('\\1',", line)
        line = re.sub("''self''", "'self'", line)
        db_column = re.findall("db_column='(.*)'", line)[0]
        line = re.sub("\)$", ", related_name='%s_%s')" % (active_model.lower(), db_column), line)
        sys.stdout.write(line)
        continue
    sys.stdout.write(line)

More like this

  1. improved generic foreign key manager by carljm 5 years, 7 months ago
  2. ForeignKey filterspec by luc_j 3 years, 7 months ago
  3. Improved generic foreign key manager 2 by Nomalz 4 years, 6 months ago
  4. DRY with common model fields (another way) by jmrbcu 6 years, 9 months ago
  5. Replace model select widget in admin with a readonly link to the related object by ekellner 5 years, 7 months ago

Comments

lauri (on April 1, 2010):

Nice idea, but it doesn't work in all cases. In particular it seems to fail in two ways for ForeignKey tables where the primary key ends in _id. Needs better re parsing.

#

(Forgotten your password?)