check database interity

 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. Cached Del.icio.us API Calls by jeffwheeler 7 years, 1 month ago
  2. MaxMind(R) GeoIP Lite CSV Import by jbronn 6 years, 9 months ago
  3. Conditional url pattern include by zbyte64 3 years, 8 months ago
  4. Setting distinction between development and public server by Archatas 7 years, 1 month ago
  5. pre_save hook for checking state changes to models by FarmKing 2 years, 5 months ago

Comments

(Forgotten your password?)