Django bulk_create() with models' fields having custom validators

In my Django application, I am using bulk_create(). For one of the fields in a target model I have assigned a set of validators to restrict the allowed value to uppercase letters (alphabets) and to a fixed length of "3", as shown below:

class Plant(models.Model):
    plant = models.CharField(primary_key=True, max_length=4, ...
    plant_name = models.CharField(max_length=75, ...
    plant_short_name = models.CharField(max_length=3, validators=[...
    # rest of the fields ...

I am restricting field plant_short_name to something like CHT for say, Plant Charlotte.

Using the source file (.csv) I am able to successfully create new instances using bulk_create, however I find that the data get saved even with field plant_short_name's value being different.

For example, if I use the source as:

9999,XYZ Plant,XY

the new instance still gets created although the length of (string) value of field plant_short_name is only 2 (instead of 3 as defined in the validators).

If I am to use an online create function (say, Django CreateView), the validators work as expected.

How do I control / rstrict the creation of model instance when a field value of incorrect length is used in the source file?

By using validators.

As described in documentation max_length is nothing more than a validator:

Required. The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.

Which means you are not restricting the minimum number of characters in the string. For that a MinLengthValidator is required.

Back to Top