Changing the size of max_length in the model is fast. But sometimes you forget to update all running systems which use this model.
This unittest helps you to find the difference between Model and DB before the users get uncaught exceptions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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))
|
More like this
- Generate and render HTML Table by LLyaudet 1 day, 21 hours ago
- My firs Snippets by GutemaG 5 days, 6 hours ago
- FileField having auto upload_to path by junaidmgithub 1 month, 1 week ago
- LazyPrimaryKeyRelatedField by LLyaudet 1 month, 2 weeks ago
- CacheInDictManager by LLyaudet 1 month, 2 weeks ago
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.
#
Please login first before commenting.