Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Change TimeField to DateTimeField in models.py

In my models.py, i have some models with this kind of attributes:

timestamp = models.TimeField(default=0)

I want to change them to:

timestamp = models.DateTimeField(default=0)

Using

python manage.py schemamigration app --auto 

works in first instance. But

python manage.py migrate app

leads to this error:

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

So i somehow needs to make this casting possible. For every time without date i want to set a default date (e.g. yesterday). How can i do this? I only found this on SO, which does not help at all because of that error. BTW: I am using postgres and python3.

I appreciate your help!

It is okay for me to use SQL direct on the database (without south) if that's easier

like image 962
svenwildermann-msft Avatar asked May 27 '14 14:05

svenwildermann-msft


People also ask

What is the format of DateTimeField in Django?

DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime. datetime object.

WHAT IS models DateTimeField?

DateTimeField is a frequently-used attribute on Model classes when defining date- and time-based database columns with the Django ORM. The Django project has great documentation for DateTimeField and all of the other column fields. Note that DateTimeField is defined within the django.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


2 Answers

That's because time cannot be converted (casted) to timestamp (neither their time-zone related variants) in PostgreSQL. F.ex. this will also fail:

SELECT 'now'::time::timestamp

In these cases, you should use the USING clause in your ALTER TABLE statement (if you can edit it directly):

ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
ALTER [ COLUMN ] column_name
[ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]

Your query will look like, f.ex.:

ALTER TABLE "my_model"
ALTER COLUMN "column_name"
SET DATA TYPE TIMESTAMP WITH TIME ZONE USING 'yesterday'::date + "column_name"
like image 63
pozs Avatar answered Sep 28 '22 08:09

pozs


If you didn't have any data in your tables, then you can delete your migrations from migrations folder of your app and change the field to DateTime then do the initial migration. My problem solved, without touching the SQL Queries

like image 25
vikas0713 Avatar answered Sep 28 '22 06:09

vikas0713