Login

check database interity

Author:
d2
Posted:
June 22, 2010
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Check database constraints after dirty import

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.db import models
from django.conf import settings
from django.db import connection



cursor = connection.cursor()
    

for app in models.get_apps():
    for model in models.get_models(app):
        for f in model._meta.local_fields:
            if(f.rel):
                sql=u"""SELECT `%(table)s`.`%(pk)s` FROM `%(table)s` LEFT JOIN `%(fk_table)s` as fkt ON fkt.`%(fk_pk)s` = `%(table)s`.`%(attname)s` WHERE not isnull(`%(table)s`.`%(attname)s`) AND isnull(fkt.`%(fk_pk)s`);""" % { 'pk': model._meta.pk.attname,
            'table': model._meta.db_table,
            'fk_table' : f.rel.to._meta.db_table,
            'fk_pk' : f.rel.to._meta.pk.attname,
            'attname': f.get_attname()
            }
                cursor.execute(sql)
                errors = len(cursor.fetchall())
                if errors:
                    print "model %s, relation %s (%s) : %s" % (model._meta.app_label+'.'+model.__name__,f.rel.to._meta.db_table, f.get_attname(), errors)
            

More like this

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

Comments

Please login first before commenting.