Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a schemamigration, what should be the default value for a null=False field which I'm sure that won't have null values?

I want to add a ForeignKey field to my model. In order to achieve that, I did 3 steps:

  1. Added the ForeignKey field with null=True to my model, and then created a schemamigration.
  2. Created a datamigration in order to fill that foreign key with a sensible value. After this migration is applied, I'm pretty sure there is no object left with a NULL value at that field.
  3. Changed that ForeignKey field to null=False, and then created another schemamigration.

However, I'm having problems at the step 3:

? The field 'MyModel.fkfield' does not have a default specified, yet is NOT NULL.
? Since you are making this field non-nullable, you MUST specify a default
? value to use for existing rows. Would you like to:
?  1. Quit now, and add a default to the field in models.py
?  2. Specify a one-off value to use for existing columns now
? Please select a choice:

Well... No default value makes sense for this field, and also by now I'm pretty sure no object has that field as NULL. So... I don't know how to answer this question correctly. If I could, I would say "don't set any default value, and throw an error if you find any NULL in that column".

For now, as a workaround just to get over that question, I'm choosing option 2 and then using 1 as the one-off default value. This is a quite bad solution, but at least south doesn't complain about it and creates the migration.

  • What is the correct way of changing a field into NOT NULL? (using south)
  • What should I do when south asks me for a default value for a field that shouldn't have one?

I'm using django-1.2 and south-0.7.


Related question: Django South - turning a null=True field into a null=False field

Related documentation: Part 3: Advanced Commands and Data Migrations

(footnote: here at StackOverflow we have two tags that seem equal for me: "django-south" and "south", but I don't have enough reputation to suggest synonyms)

like image 864
Denilson Sá Maia Avatar asked Jun 20 '11 03:06

Denilson Sá Maia


1 Answers

Just a thought: Since this is a foreign key, you can set the default value to a record you know will never have a referenced record, i.e. 0 or -1. Your db will raise an error if south will actually try to use this default.

like image 199
Udi Avatar answered Nov 09 '22 06:11

Udi