[Answered ]-Charfield null errors

2👍

If you don’t specify the supplier_name, e.g. Supplier.objects.create(unique_id=1, name='example'), then I would expect supplier_name to be saved as an empty string.

However, if you explicitly set supplier_name=None, e.g.
Supplier.objects.create(unique_id=2, name='example2', supplier_name=None), then Django will try to save null and you will get the IntegrityError.

Note that the blank=True option affects model forms and the Django admin. It doesn’t affect the underlying database schema, or automatically convert None to ''.

The reason that Two Scoops and the Django Docs recommend null=False is so that '' is the only value for ‘no data’. If you have null=True then there are two values for ‘no data’, '' and None.

One good reason to use null=True is if you want to make the field unique, but allow empty values.

In your case, it’s hard to say what you should do because you haven’t shown the code. Ideally, keep null=True to stick with the Django convention. You could then modify your code so that you don’t set supplier_name=None, or convert it with supplier_name = supplier_name or ''.

0👍

If your fine with keeping that field as null then use null=True another advantage of using null=true you will not fetch future updation error when ever you will add other filed in your same model then every time you need to tell for default value so it’s better to use null=true to avoid it.

0👍

If you don’t want a null value, provide a default value to the field:

supplier_name = models.CharField(max_length=255, default='', blank=True)

https://docs.djangoproject.com/en/3.0/ref/models/fields/#default

Leave a comment