0
votes

I have a OnetoOne field with primary_key=True in a model. Now I want to change that to a ForeignKey but cannot since there is no 'id'.

From this:

user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)

To this:

user1 = models.ForeignKey(User, related_name='questionnaire', on_delete=models.CASCADE)

Showing this while makemigrations:

You are trying to add a non-nullable field 'id' to historicaluserquestionnaire without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py

So how to do that? Thanks!

2
What if you try allowing nulls like null=True, or set a default user as default=<have your default user here>Adil Shirinov
No its the same thing because primary key was True so there was no id to those objectsHarshit verma

2 Answers

0
votes

just delete your previous migrations

e.g 

    migrations:
          |
          |- 001.initail.py
          |- 002.examplefiles.py

you just have to delete you most recent migrations and

run the command

python3 manage.py makemigrations
python3 manage.py migrate
0
votes

Django models have a default ID attribute. Since you changed the model, the previous data records has now conflicts with your new column attributes because when previous records were added, there were no ForeignKey. Remember, In your foreignkey, null values are not allowed. There are multiple fixes to your solution. Follow these step one-by-one and see what resolves your eror.

  • Delete your migrations file and run migrations again

Set NULL=True in your foreign key

OR

Delete previous records of the table to resolve the conflict, so that when you run migrations, it adds a default value of id itself

instead of deleting, you can also try and change your migrations files directly like this

https://stackoverflow.com/a/29074241/11979793