During development, I learned that a little operation is required when adding items to an existing model later, so I summarized that knowledge.
First, for simplicity, let's assume you have a simple model like this:
class NameModel(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
Consider adding an item using DateField ()
here.
Add items as shown below.
class NameModel(models.Model):
name = models.CharField(max_length=50)
date = models.DateField() #add to
def __str__(self):
return self.name
I changed the model, so I will migrate it.
$ python manage.py makemigrations
At this point, you will see a message similar to the following.
You are trying to add a non-nullable field 'date' to NameModel 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:
This message means I'm trying to add a null date
but I can't, and I have to choose between two options to resolve it.
This is caused by the fact that the item "date" does not exist to enter the original data, so the contents have become null.
Since 2) is an option to recreate the model, we will select 1) here.
Then
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>>
It will be displayed. What does this put for date? So here we add timezone.now according to the instructions.
that's all.
This can also be avoided by setting null = True
in the argument of DateField
.
If you have any problems, please let us know.
Recommended Posts