datetime字段不能与django 1.8一起迁移

时间:2016-06-06 15:03:53

标签: django database-migration django-1.8

自升级到django 1.8以来,我的模型中的日期时间字段存在一些问题,无法正确迁移。

我反复看到这个消息:

Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

我运行makemigrations,我明白了:

operations = [
    migrations.AlterField(
        model_name='profile',
        name='date_of_hire',
        field=models.DateField(default=datetime.date(2016, 6, 5)),
    ),
]

所以我运行manage.py migrate然后我得到:

Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

所以我再次运行make migrations,我得到一个与上面相同的新迁移。

这是我的问题领域:

date_of_hire = models.DateField(default=datetime.date.today())

查看迁移我可以看到日期已明确设置为固定日期。所以现在如果我改变我的字段:

date_of_hire = models.DateField(auto_now_add=True)

或者这个:

date_of_hire = models.DateTimeField(auto_now_add=True)

尝试运行makemigrations或启动服务器时,我收到以下错误:

File "/urls.py", line 13, in <module>
import profiles.views as profile_views
File "/profiles/views.py", line 9, in <module>
from profiles.forms import CompanyProfileForm
File "/profiles/forms.py", line 19, in <module>
class ProfileForm(ModelForm):
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 295, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (date_of_hire) specified for Profile

如果我在forms.py字段列表中注释掉该字段除了表单之外的所有内容。我可以进行迁移并应用它们,运行服务器等等,但是一旦取消注释该字段,应用程序就会废话。所以我不知所措......

1 个答案:

答案 0 :(得分:1)

default中,您应该传递可调用的datetime.date.today,而不是调用它:

date_of_hire = models.DateField(default=datetime.date.today)

当您使用default=datetime.date.today()时,Django会在您每次加载today()时调用models.py。这改变了默认值,因此Django认为需要进行新的迁移。

您必须再创建一次迁移,将默认值更改为datetime.date.today(或修改现有迁移,但这样会更棘手)。