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
- Image compression before saving the new model / work with JPG, PNG by Schleidens 6 days, 4 hours ago
- Help text hyperlinks by sa2812 1 month ago
- Stuff by NixonDash 3 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago
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.