My question is, what is the best practice for turning a null=True
field into a null=False
field using Django South. Specifically, I'm working with a ForeignKey
.
The fundamental difference between these two is that null controls the validation at the database level, and blank is used during form field validation at the application level. By default all fields are required. In order to make a field optional, we have to say so explicitly.
null=True will set the field's value to NULL i.e., no data. It is basically for the databases column value. blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms.
The Django convention is to use the empty string, not NULL. The default values of null and blank are False. Also there is a special case, when you need to accept NULL values for a BooleanField , use NullBooleanField instead.
If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
You should write first a data migration: http://south.aeracode.org/docs/tutorial/part3.html and then make the schemamigration.
If you want to turn nullable ForeignKey into non-nullable one, then it can be problematic if you have any rows with NULL for that field (column). In such case you need to either remove or fix them - possibly with custom data migration, like diegueus9
mentioned in the other answer.
But if you don't have any rows with NULL in that column, e.g. because you put that null=True only in case you might need it in the future, then you should be able to do a simple automatic schema migration:
$ ./manage.py schemamigration myapp remove_null_from_fkey --auto
(...)
$ ./manage.py migrate myapp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With