Changing DateField to DateTimeField in Django

折月煮酒 提交于 2019-12-10 18:02:20

问题


In my current models file for my app I've got some publish date fields, start and end date. However I'd like to change them from DateFields to DateTimeFields. This will give the user a little more flexibility when setting a publish date, as they would like to specify a time.

I'm using south to do the database migrations, will I have any problems when changing the field in the database? Or will need to remove it? Then add it as a DateTimeField?

Once I've done that, will i be able to set a default time? for example I'd like the start date to start at 9 in the morning. and the end date to finish at midnight.

Anyway here are the models i'd like to change.

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

I'd like to change to:

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

Any help would be appreciated.


回答1:


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.




回答2:


You can easily do that with south:

python manage.py schemamigration --auto appname

The whole column will start at midnight (eg, 2013-09-26 -> 2013-09-26 00:00:00). To change the hour, edit your migration, and after the column has been changed, put:

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))

As for the end_date, it will already start at midnight, but if you want to set it to 23:59:59, you may also add datetime.timedelta(hours=23, minutes=59, seconds=59) or simply datetime.timedelta(seconds=86399), which is less readable.



来源:https://stackoverflow.com/questions/19027444/changing-datefield-to-datetimefield-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!