Reputation: 794
I've started learning Django from a YouTube course.
In the models.py file, there are two classes.
class Album(models.Model):
artist = models.CharField(max_length = 250)
album_title = models.CharField(max_length = 250)
album_logo = models.CharField(max_length = 1000)
def __str__(self):
return self.album_title + ' - ' + self.artist
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
genre = models.CharField(max_length=250)
def __str__(self):
return self.song_title
I added the genre in the Song after the migration. That's why I'm having problem while adding data. In the interactive shell, if I try to save() , it shows there's no 'genre' field. If I try to migrate again, it shows something like this:
You are trying to add a non-nullable field 'genre' to song 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 Select an option:
What's the proper way of adding or deleting fields?
Upvotes: 1
Views: 2370
Reputation: 6276
add default=""
to genere field
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
genre = models.CharField(max_length=250, default="")
def __str__(self):
return self.song_title
As the error message shows, you add a field genre
to Song
model without adding default=""
nor null=True
parameters to it. When you migrate it, django don't know how to deal with the old data that has been inserted into the database without genere field. So you should set them to null with null=True
or other default value with default=""
.
You can also just keep your code. But when you use the migrate command, you should tell django that you will give a default value like the django recommanded:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
press 1
and enter
key. input ""
and then django will set all the old data genre=""
.
Upvotes: 3