W rzeczywistości był to bardzo dobry i pouczający artykuł na ten temat. Tutaj: http://ianrolfe.livejournal.com/36017.html
Rozwiązanie na stronie jest nieco przestarzała, więc robiłam następujące:
from django.db import models
from datetime import datetime
from time import strftime
class UnixTimestampField(models.DateTimeField):
"""UnixTimestampField: creates a DateTimeField that is represented on the
database as a TIMESTAMP field rather than the usual DATETIME field.
"""
def __init__(self, null=False, blank=False, **kwargs):
super(UnixTimestampField, self).__init__(**kwargs)
# default for TIMESTAMP is NOT NULL unlike most fields, so we have to
# cheat a little:
self.blank, self.isnull = blank, null
self.null = True # To prevent the framework from shoving in "not null".
def db_type(self, connection):
typ=['TIMESTAMP']
# See above!
if self.isnull:
typ += ['NULL']
if self.auto_created:
typ += ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP']
return ' '.join(typ)
def to_python(self, value):
if isinstance(value, int):
return datetime.fromtimestamp(value)
else:
return models.DateTimeField.to_python(self, value)
def get_db_prep_value(self, value, connection, prepared=False):
if value==None:
return None
# Use '%Y%m%d%H%M%S' for MySQL < 4.1
return strftime('%Y-%m-%d %H:%M:%S',value.timetuple())
Aby go użyć, wszystko co musisz zrobić, to: timestamp = UnixTimestampField(auto_created=True)
W MySQL kolumna powinna wyglądać następująco: 'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
Jedyną wadą jest to, że działa tylko w bazach danych MySQL. Można go jednak łatwo modyfikować dla innych.
Opcja 'funkcja get_db_prep_value' jest nieaktualny, ponieważ odnosi się tylko do Kolumny "TIMESTAMP" w MySQL <4.1. Dla współczesnych wersji MySQL użyj '% Y%% m% d% H:% M:% S'' zamiast'% Y% m% d% H% M% S''. – CoreDumpError
Dla django 1.8 należy zaimplementować wartość from_db_value, aby przekonwertować wartość bazy danych na atrybut obiektu. –