3

在我当前的应用程序模型文件中,我有一些发布日期字段、开始日期和结束日期。但是我想将它们从 DateFields 更改为 DateTimeFields。这将在设置发布日期时为用户提供更多灵活性,因为他们希望指定时间。

我正在使用南进行数据库迁移,在更改数据库中的字段时会出现任何问题吗?还是需要删除它?然后将其添加为 DateTimeField?

完成后,我可以设置默认时间吗?例如,我希望开始日期从早上 9 点开始。以及在午夜完成的结束日期。

无论如何,这里是我想改变的模型。

start_date = models.DateField()
end_date = models.DateField()

我想改为:

start_date = models.DateTimeField()
end_date = models.DateTimeField()

任何帮助,将不胜感激。

4

2 回答 2

3

It turns out when you change a DateField to a DateTimeField south will just change it for you so it won't conflict.

For example I ran:

python manage.py schemamigration --auto hotel

and got this output:

 ~ Changed field start_date on hotel.Event
 ~ Changed field end_date on hotel.Event
Created 0018_auto__chg_field_event_start_date__chg_field_event_end_date.py. You can now apply this migration with: ./manage.py migrate hotel

Although i would advide backing up the database before making any changes.

于 2013-09-26T12:07:14.130 回答
0

你可以很容易地用南做到这一点:

python manage.py schemamigration --auto appname

整列将从午夜开始(例如2013-09-26-> 2013-09-26 00:00:00)。要更改小时,请编辑您的迁移,并在更改列后,输入:

import datetime
from django.db.models import F

# ... Automatically created db.alter_column

if not db.dry_run:  # needed whenever making data changes
    # This will add 9 hours to *all* records
    orm['appname.ModelName'].objects.all().update(start_date=F('start_date') + datetime.timedelta(hours=9))

至于end_date,它已经在午夜开始了,但如果你想将它设置为23:59:59,你也可以添加datetime.timedelta(hours=23, minutes=59, seconds=59)or datetime.timedelta(seconds=86399),这不太可读。

于 2013-09-26T12:45:34.313 回答