5

MySQL的5.6.4和向上膨脹分數秒支持TIME,DATETIME和時間戳值,具有高達微秒(6位)精度:http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html如何創建Django自定義字段來存儲MYSQL DATETIME(6)並在Django/MySQL中啓用小數秒(毫秒和/或微秒)?

Django的1.5和最多支持分數秒爲imputformat:https://docs.djangoproject.com/en/1.5/ref/settings/#datetime-input-formats

但是DATETIME(6)字段尚未在Django中實現。 https://code.djangoproject.com/ticket/19716

我決定寫一個自定義的DateTimeFractionField。它是帶DATETIME([1-6])db_type的標準DateTimeField。 'precicion'是設置毫秒,微秒或任何其他分數精度。

class DateTimeFractionField(models.DateTimeField): 
    description = "Datetimefield with fraction second." 

    def __init__(self, precision, *args, **kwargs): 
     self.precision = precision 
     super(DateTimeFractionField, self).__init__(*args, **kwargs) 

    def db_type(self, connection): 
     return 'DATETIME(%s)' % self.precision 


class MyModel(models.Model): 
    dt_micros = DateTimeFractionField(6) 
    dt_millis = DateTimeFractionField(3) 
    dt = models.DateTimeField() 

    def __unicode__(self): 
     return "%s - %s" %(self.dt_micros, self.dt_millis) 

mysql後端負責用0替換毫秒。Django文檔建議寫我自己的後端。 https://docs.djangoproject.com/en/1.5/ref/settings/#engine

我被黑:

​​

和改性mysql564/base.py:

線42:45

from django.db.backends.mysql564.client import DatabaseClient 
from django.db.backends.mysql564.creation import DatabaseCreation 
from django.db.backends.mysql564.introspection import DatabaseIntrospection 
from django.db.backends.mysql564.validation import DatabaseValidation 

線167

supports_microsecond_precision = True 

214線

compiler_module = "django.db.backends.mysql564.compiler" 

線357

return six.text_type(value) #value.replace(microsecond=0) 

線368

return six.text_type(value) #value.replace(microsecond=0) 

線373

return [first, second] #return [first.replace(microsecond=0), second.replace(microsecond=0)] 

然後我激活了新的後端在settings.py:

'ENGINE': 'django.db.backends.mysql564', 

當我在admin中添加並保存我的模型時,值會保存到de db! :)

Sequel Pro

但他們不返回(無 - 無空表單域)。 :(

Django admin

我是什麼在這裏失蹤?

  1. 不會返回爲什麼DateTimeFractionField值?
  2. 有沒有更好的(簡單)的方式來實現支持餾分DateTimeField字段?

我知道還有其他db的支持分數。但是我喜歡使用MySQL並且讓票更接近固定。

UPDATE:

它不(僅)的形式,從德分貝得到一個DateTime對象失敗。

In [1]: from spacetime.models import MyModel 

In [2]: from django.shortcuts import get_object_or_404 

In [3]: get_object_or_404(MyModel, pk=1).dt 
Out[3]: datetime.datetime(2013, 7, 25, 0, 22, 23) 

In [4]: get_object_or_404(MyModel, pk=1).dt_millis 

In [5]: get_object_or_404(MyModel, pk=1).dt_millis.__class__ 
Out[5]: NoneType #This should be datetime.datetime 
+0

返回UTC也許這只是我,但它是一種混亂的,看看你是什麼樣的交流要求/試圖去做。 – jdero

+0

我嘗試創建支持小數秒的DateTimeField。我的自定義DateTimeField是DateTimeFractionField。它成功地將日期時間對象與分數保存到數據庫中,但從數據庫獲取值到Django不起作用。總體目標是獲得一個工作的DateTimeFractionField字段。目前的問題是:爲什麼DateTimeFractionField值不返回? – allcaps

+0

據我所知,Django並不支持它,因爲SQL沒有真正的規範。您可以使用CharField,或編寫使用特定於數據庫的代碼的自己的字段。 – stormlifter

回答

1

我已經試過這成功地,但我的做法是完全不同的: 我分裂的DateTimeField字段(UTC)的信息和IntegerField(微秒= US):

from datetime     import datetime, timedelta 
import pytz 

class MyModel (models.Model): 
    # My model stuff and other fields here 
    _UTC = models.DateTimeField() 
    _uS = models.IntegerField() 

然後我在班上設置屬性與微秒和區域信息感知(因爲我的數據庫不支持時區信息)

@property 
    def UTC (self): 
     utc = self._UTC 
     us = self._uS 
     # add microseconds 
     utc += timedelta(microseconds=us) 
     return utc.replace(tzinfo=pytz.utc) 
    @UTC.setter 
    def UTC (self,utc): 
     self._UTC = utc-timedelta(microseconds=utc.microsecond) # without microseconds 
     self._uS = utc.microsecond 
+0

不錯。我會試試這個。 Django 1.8將支持fraction:https://docs.djangoproject.com/en/dev/releases/1.8/#database-backends – allcaps

+0

請注意@property字段不適用於篩選查詢(MyModel.objects。過濾器(UTC ...)。對於此用途,需要分別按_UTC和/或_uS進行過濾 – Anr