Reputation: 145
I've got the following models:
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Ingredient(models.Model):
ingredients_recipe = models.ForeignKey(Post, on_delete=models.CASCADE)
type = models.CharField(max_length=50)
quantity = models.IntegerField()
measurement = models.CharField(max_length=50)
class MethodStep(models.Model):
methods_recipe = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
step = models.TextField()
When i try to run makemigrations
, i get no errors for the Ingredient
class, but on the MethodStep
class i get an error saying:
You are trying to add a non-nullable field 'methods_recipe' to methodstep without a default; we can't do that (the database needs something to populate existing rows).
Can someone help me? I'm not sure whats different about each of these classes which would mean the MethodStep
has an error but Ingredient
doesn't.
Edit: I've also tried deleting/clearing/removing the db but the error persists everytime makemigrations
is run.
Upvotes: 0
Views: 2696
Reputation: 58
Sometimes in addition to resetting the database you will also have to remove all existing Migrations from your project (or at least the ones for the package these models belong to).
Delete all files in the migrations folder EXCEPT for the _init__.py file.
When simply dumping your db and restarting django, startup will apply the migration history in the order they were created.
That means if you added this ForeignKey Field after already migrating changes to the db, django won't let you migrate without a default unless you delete the migration history.
Upvotes: 3
Reputation: 101
This happens after you create a model field.
This is because you have added rows/objects in the table/model since your last migration.
Django is aware of table rows in your db and and cannot figure out what to fill the new field with for the old rows. To fix this, depending on the type of field you created newly, update the field adding: default=None :if you don't mind those fields having nothing to go with otherwise consider some default string or int or float consistent with the field going forward AND also add blank = True
To take everything back to square one, apart from deleting your db, you will also need to delete associated migration files. If you are not sure which it is, delete all of them but do not touch the init file in the folder. Then makemigrations and migrate.
PS: I'm sure you know that with the last approach you lose all records in the model.
Upvotes: 1