user1427661 user1427661 - 3 months ago 25
Python Question

The field does not have a default specified, yet is NOT NULL

I have no idea what Django is trying to tell me. I have a model,

WeekTwo
, which inherits from
Week
, which inherits from
modelsModel
. I have another model,
UserProfile
. I want to use
WeekTwo
as a OneToOne Key in
UserProfile
, so I inserted the following line of code:

weekTwo = models.OneToOneField(WeekTwo)


However, when I try to migrate my database using
python manage.py schemamigration my_app --auto
, I get the following error:

The field 'UserProfile.weekTwo' does not have a default specified, yet is NOT NULL.


I tried adding
default=0
to my
weekTwo
declaration, but now I'm getting this error when I try the schema migration:

IntegrityError: column weekTwo_id is not unique


Moreover, south is now telling me that I am in an
interim state between migrations
and that I
might be able to recover
. I literally have no idea what any of this means.

Answer

Be aware before going further, be sure that if South already did any migration that has been failed, It's better to redo|recover to the last migration that was working.

You have two options here, at first you can do Data Migration. Look at ref also.

In Second way You can make weekTwo field null and blank first

weekTwo = models.OneToOneField(WeekTwo, null=True, blank=True)

Then let South generate a migration for you by

python manage.py schemamigration my_app --auto

I'm sure South won't complain about it now, Then

python manage.py migrate

If everything is okay now, You can now get back and change to weekTwo field to

weekTwo = models.OneToOneField(WeekTwo)

And generate migration then migrate them.

Anyway, When south find out your field in not NULL and doesn't have a default value, at the schemamigration step it will suggest you to provide a value for it, Again here your field is OneToOneField, because even south gives you chance to provide a default value for your existed record on model again uniqueness of weekTwo field will raise an error.

I think still you have to go with Data Migration if second way didn't work, Or gives it a shot and try the second way this time instead of make it null, blank change the whole Field type. Try it with;

weekTwo = models.ForeignKey(WeekTwo)

But keep in mind Data migration would be definitely smarter and standard way here.