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)