【问题标题】:datetime fields not migrating with django 1.8日期时间字段不与 django 1.8 一起迁移
【发布时间】:2016-10-06 06:11:34
【问题描述】:

自从升级到 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 字段中注释掉该字段,则会列出除表单有效之外的所有内容。我可以进行迁移并应用它们,运行服务器等等,但是一旦我取消注释该字段,应用程序就会废话。所以我很茫然……

【问题讨论】:

    标签: django database-migration django-1.8


    【解决方案1】:

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

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

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

    您必须再创建一个迁移以将默认值更改为 datetime.date.today(或编辑现有迁移,但这会比较棘手)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-29
      • 2015-11-24
      • 2012-04-21
      • 2015-01-28
      • 1970-01-01
      • 2015-07-11
      • 2016-02-10
      • 2015-09-08
      相关资源
      最近更新 更多