django.db.utils.DataError: value too long for type character varying(7)

Everything was working right, at a certain moment I changer the max_length for a CharField to 7, and it gave me this error when I try to migrate:

django.db.utils.DataError: value too long for type character varying(7)

Now that I’ve canceled the changes, when I try to migrate, I keep getting the same error, ANY SOLUTIONS PLEASE ?

First, check to see if that migration was applied. (manage.py showmigrations). If it wasn’t (and I’m expecting it wasn’t), I believe the easiest solution would be for you to edit that migration file and change that migration to a more appropriate value for that field.

The error is due to data in your database being longer than 7 characters. You may want to look at the data and consider fixing it or whether 7 characters is really the limit you want.

one of your rows has that colum at 8 characters or more.
Make sure none of them do before migrating. Potentially by listing of the values for all your objects, something like (extremely quick and dirty):

objs = Model.objects.all().values(
    'pk',
    'your_problematic_field'
)
for obj in objs:
    l = len(obj['your_problematic_field'])
    if len(l) > 7:
        print(f'obj with id {obj["pk"]} has that field at {l} characters long')

do indeed run manage.py showmigrations

if your migration does show up, you will I think need to manually remove it from the table django_migrations. A simple DELETE FROM is quick and easy.

Couldn’t help it, better way: :slight_smile:

from django.db.models.functions import Length
objs = Model.objects.annotate(
    your_problematic_field_length=Length('your_problematic_field')
).filter(
    your_problematic_field_length__gt=7
).values(
    'pk',
    'your_problematic_field',
    'your_problematic_field_length',
)
for obj in objs:
    print(f'obj with id {obj["pk"]} has that field at {obj["your_problematic_field_length"]} characters long')