In a comment to this question answer I asked how to remove a field with a default value function. To sum up, the example code is:
def get_deadline():
return datetime.today() + timedelta(days=20)
class Bill(models.Model):
name = models.CharField(max_length=50)
customer = models.ForeignKey(User, related_name='bills')
date = models.DateField(default=datetime.today)
deadline = models.DateField(default=get_deadline)
and my question to the code is:
How do you remove the
deadline
field again while also deleting theget_deadline
function? I have removed a field with a function for a default value, but now Django crashes on startup after removing the function. I could manually edit the migration, which would be ok in this case, but what if you simply changed the default function, and wanted to remove the old function?
I ended up removing the default part of the migration that referred to it, but how do you remove it nicely?
The only way I can think of is to squash the migrations, such that the migration using the function disappears, but that is not always an option.
Following the documentation from Historical Models:
References to functions in field options such as
upload_to
andlimit_choices_to
and model manager declarations with managers havinguse_in_migrations = True
are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations......
To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files.
Using a method to get the value of default
field option is same as what is described for upload_to
field. The documentation itself provide two options to you if you want to remove the method:
Updates from comments:
In Step 2 of Edit migration file, I have just included the way described in the documentation. How exactly you edit the migration is your choice. You could copy the function in the migration file and edit the reference or you could just remove the default field from the migration file, or you could use another function from a different file.
It looks like you've pretty much figured out the answer for yourself. Before you remove the get_deadline
function, you must remove it from any migrations that use it. There are two ways to do this:
get_deadline
to use a different default.get_deadline
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With