Login

inspectdb fixer

Author:
kriberg
Posted:
May 12, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This snippet parses the output file of inspectdb and does some alterations. Mostly useful for people who regenerates models from constantly changing legacy databases.

The snippet will:

*Add quotes around foreign key classes, so the ordering is not significant

*Append a related_name property to each foreign key with the value model class name + db_column name to evade collisions in reverse queries like:

example.model: Reverse query name for field 'foreignkey' clashes with related field 'model2.foreignkey'. Add a related_name argument to the definition for 'foreignkey'.

There's a slight performance degradation with using quotes class name instead of passing the class though.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.

#

Please login first before commenting.