I encountered a bug while working with Django migrations that I wanted to bring to your attention. The issue arises when reducing the max_length of a CharField after creating instances of the model. Here's a detailed description:
Steps to Reproduce:
-
Create a model with a
CharField:word = models.CharField(max_length=10, blank=True) -
Create an instance of this model with a
wordvalue containing 8 characters. -
Modify the model to reduce the
max_length:word = models.CharField(max_length=5, blank=True) -
Run
makemigrations. The command completes successfully and generates a migration file. -
Run
migrate. This command fails with the following error:django.db.utils.DataError: value too long for type character varying(5)
Observations:
- The error occurs because there is an existing instance with a
wordvalue longer than 5 characters. - The
makemigrationscommand does not raise any issues, but themigratecommand fails due to the existing data. - If no instances exist when reducing
max_length, the migration proceeds without errors.
Impact:
This issue could lead to significant problems if migrations are generated on a local machine without data but fail in production environments with existing data.
Potential Solution:
I don't know 🙂