3

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.

JDavies
  • 2,730
  • 7
  • 34
  • 54

2 Answers2

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.

JDavies
  • 2,730
  • 7
  • 34
  • 54
0

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.

augustomen
  • 8,977
  • 3
  • 43
  • 63