import unittest from django.db import connection from django.db.models.loading import get_models class MaxLengthTest(unittest.TestCase): def testMaxLength(self): ''' Compare max_length of model with size in the database. ''' cursor=connection.cursor() errors=[] for cls in get_models(): for field in cls._meta.fields: max_length=getattr(field, 'max_length', None) if not max_length: continue column=field.db_column or field.column if not column: continue cursor.execute('''SELECT "%s" from "%s" LIMIT 0''' % (column, cls._meta.db_table)) for name, type_code, display_size, internal_size, precision, scale, null_ok in cursor.description: if max_length!=internal_size: errors.append('%s %s.%s Python Model max_length: %s Internal Size: %s' % ( cls, cls._meta.db_table, column, max_length, internal_size)) if errors: raise Exception('\n'.join(errors))