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))
Comments
What database are you using there? That doesn't work in MySQL. First off, you can't use double quotes for quoting identifiers in MySQL (have to use backticks). Furthermore, even with that corrected, I always get internal_size to be reported 3x the max_length parameter.
But other than that, I like the idea :)
#
I use postgresql and psycopg2. I am sorry if it does not work for you. Since I don't have MySQL here, I can't update this snippet. Please send me a patch if you got it working for you.
#