dev-jim
dev-jim

Reputation: 2524

Django Migrate - change charfield to datetimefield

I have a charfield in a model that I wanted to change to Datetimefield.

From

days = models.CharField(max_length=100)

To

days = models.DateTimeField(blank=True, null=True)

But when I using the migrate command, it gives me this error.

django.db.utils.ProgrammingError: column "days" cannot be cast to type timestamp with time zone

I am using Django 1.7.

Upvotes: 0

Views: 2554

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 49092

Django's approach to timezone handling is to convert all datetimes to UTC and then store them in the database without any timezone information. Apparently your CharFields include a timezone field.

One approach would be to edit the migrations file produced by makemigrations and insert a RunPython command as the first operation. Use that to convert your CharFields to a string UTC version without timezones. That might look something like this:

from django.utils.dateparse import parse_datetime
from django.utils import timezone

days_aware = parse_datetime(days)
days_utc = days_aware.astimezone(timezone.utc)
days_naive = days_utc.replace(tzinfo=None)
days = str(days_naive)

Alternatively, instead of changing the string representation, you could instead create the DateTimeField as a new field (say days_dt); do a RunPython data migration where you convert the string to a datetime (days_dt = parse_datetime(days)); delete the days field; and rename days_dt to days. That would also work and would leave Django in charge of representing datetimes at the database level.

Upvotes: 1

amanhuipg
amanhuipg

Reputation: 175

I haven't tested it but probably you should do something like this posts explain: South migrate DateField to IntegerField or Django south: changing field type in data migration

Upvotes: 0

Related Questions