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. SelectRelatedManager by realmac 1 year, 9 months ago
  2. A small script to rearranging the models generated from inspectdb command by m_tayseer 4 years, 7 months ago
  3. Allow foreign key attributes in list_display with '__' by jcushman 4 months, 2 weeks ago
  4. Decoupling models with cross-database relations by zvikico 2 years, 4 months ago
  5. improved generic foreign key manager by carljm 4 years, 8 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?)