Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide a default for ForeignKey field on existing entries in Django

I have this model:

class Movie(models.Model):
    # here are some fields for this model

to which I added the following field (the database was already populated with Movie models):

user = models.ForeignKey(User, default=1)

I ran the commands 'makemigrations' and then 'migrate':

python manage.py makemigrations myapp
python manage.py migrate 

but it doesn't work. What I want to do is to add the 'user' field to Movie objects and provide a default for it for all the existing Movie objects in my database (in this case the default is the User object with id=1).
Another thing that I tried is to leave it without the default value and then, when i run the 'makemigrations' command, to give it the default value 1 (by selecting the "provide a one-off default now" option). In both cases, when I run the 'migrate' command I get an IntegrityError:

django.db.utils.IntegrityError: movies_movie__new.user_id may not be NULL

I also checked the ids for the Users that are already in the database to make sure that a User with id=1 exists and it does. So why doesn't it work? Thank you.

like image 900
Kaladin11 Avatar asked Mar 16 '15 03:03

Kaladin11


1 Answers

If you add "null=True" it works:

user = models.ForeignKey(User, default=1, null=True)

Then

python manage.py makemigrations movies

Migrations for 'movies':
0003_auto_20150316_0959.py:
...
- Add field user to Movie
...

Then

python manage.py migrate movies

The database should look like:

id|user_id|name
1|1|movie_name
2|1|movie_2
3|1|movie_3
...

All the empty user_ids get a value of 1. So you're done.

Now, if you need to make that field required, just change the model back to

user = models.ForeignKey(User, default=1)

make another migration and migrate again

This time it will work since all fields have user_id.

;-)

like image 178
brunofitas Avatar answered Sep 28 '22 01:09

brunofitas