Reputation: 96
I added the field user
which is a foreign key to another model called User
. This field was added to the model called Bid
. However, when I tried to migrate the changes, I got the message:
It is impossible to add a non-nullable field 'user' to bid without specifying a default. This is because 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 manually define a default value in models.py.
Last time, I set it to 'user'
and got an error that stated: ValueError: invalid literal for int() with base 10: 'user'
.
What should I set the default value as?
models.py:
class Bid(models.Model):
item = models.ForeignKey(Listing, on_delete=models.CASCADE)
price = models.FloatField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
Upvotes: 1
Views: 787
Reputation: 3381
If you add a relationship via a new foreign key, you have two options
NULL
(i.e. None
in python). This way, legacy entries with unknown relations will have NULL
as the FK, i.e. do not know their users.Bid
records. This requires that you have kept that information beforehand.Upvotes: 1
Reputation: 779
As the error says, you are creating a new field in your table. When creating a new field, existing rows need to be taken into consideration. Safest approach is to set it as null=True
and handle the field later.
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
However you may not want a Bid
to have a null user. In which case I recommend looking into how to write a custom migration to populate existing rows.
Another note: if the data you have in your table is not needed, you could consider dropping the table and rebuilding it or deleting your migrations and creating them again with manage.py makemigrations
- again only if the data you have in your db is not needed.
Upvotes: 1