9

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.

El Bert
  • 2,958
  • 1
  • 28
  • 36
Kaladin11
  • 195
  • 1
  • 2
  • 7
  • Well, the default value only applies on new objects. As for the previous records, that value will be null, I guess! Try to add a "null=True" on the model. – brunofitas Mar 16 '15 at 09:44
  • Yeah. There needs to be an option 3. Delete objects that raise Integrity Error. This would be pretty handy early on in the development when you don't really care about the data that much. – Shashwat Black Jan 03 '19 at 11:22

1 Answers1

14

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.

;-)

brunofitas
  • 2,983
  • 1
  • 20
  • 26
  • I added null=True, but I still get the IntegrityError. I tried that before asking the question as well. – Kaladin11 Mar 16 '15 at 19:19
  • I just reverted the project to a previous commit and added again all the fields that I wanted and now it worked fine. I don't know what the problem was since I was getting the IntegrityError everytime, even after I deleted that foreign key field. Thank you, anyway :) – Kaladin11 Mar 16 '15 at 23:41
  • I add `null=True` and `blank=True`. – AnonymousUser May 20 '22 at 05:26