Django bulk_create() with models' fields having custom validators

553 views Asked by At

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:

plant,plant_name,plant_short_name
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?

1

There are 1 answers

2
Niko On

bulk_create():

This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are). Also, does not call save() on each of the instances, do not send any pre/post_save signals.

By efficient manner it means there is no validation. You can explore more of the function code in django/models/db/query.py inside the environment.