0

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.

dev-jim
  • 2,404
  • 6
  • 35
  • 61

2 Answers2

1

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.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • I have tried the second option. Since it is still at development stage and the value in `days` doesn't matter. So I completely delete the `days` field and add a new `new_days` field, but still I got the `column "days" cannot be cast to type timestamp with time zone` – dev-jim Oct 16 '14 at 11:49
  • @dev-jim: Did you delete the old migration file? Anyway, if you don't care about preserving data you can make this even easier. Just delete the field, run `makemigrations`, and then re-add `days` as a `DateTimeField` and run `makemigrations` again. – Kevin Christopher Henry Oct 16 '14 at 17:11
0

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

Community
  • 1
  • 1
amanhuipg
  • 175
  • 2
  • 10