溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在Django中添加沒有微秒的 DateTimeField屬性詳解

發(fā)布時(shí)間:2021-02-08 09:34:42 來源:億速云 閱讀:204 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下怎么在Django中添加沒有微秒的 DateTimeField屬性詳解,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

前言

今天在項(xiàng)目中遇到一個(gè)Django的大坑,一個(gè)很簡單的分頁問題,造成了數(shù)據(jù)重復(fù)。最后排查發(fā)現(xiàn)是DateTimeField 屬性引起的。

下面描述下問題,下面是我需要用到的一個(gè) Task Model 基本定義:

class Task(models.Model):
 # ...... 省略了其他字段
 title = models.CharField(max_length=256, verbose_name=u'標(biāo)題')
 created_at = models.DateTimeField(auto_now_add=True, verbose_name=u'創(chuàng)建時(shí)間')

問題描述

前端這邊的分頁方式不是常規(guī)的 page、page_size 方式,而是使用標(biāo)志位的方式進(jìn)行分頁,我這里采用的就是通過創(chuàng)建時(shí)間的時(shí)間戳作為分頁標(biāo)記。比如下面是返回的第一頁的數(shù)據(jù):

{
 "data": {
 "count": 5,
 "has_next": 1,
 "tasks": [
 {
 "title": "這是一個(gè)作業(yè)標(biāo)題1",
 "ts": 1546829224000,
 "id": 1
 },
 {
 "title": "這是一個(gè)作業(yè)標(biāo)題2",
 "ts": 1546829641000,
 "id": 2
 }
 ]
 },
 "result": 1
}

要請(qǐng)求第2頁的數(shù)據(jù)只需要在請(qǐng)求的 API 中傳遞上一頁最后一條數(shù)據(jù)的時(shí)間戳即可,這里我們就傳遞 1546829641000,這樣當(dāng)我后臺(tái)接收到這個(gè)值過后就直接過濾大于該時(shí)間戳的數(shù)據(jù),再取一頁數(shù)據(jù)返回前端即可,邏輯上很簡單。過濾核心代碼如下:

ts = string_utils.get_num(request.GET.get('ts', 0), 0)
alltask = Task.objects.filter(created_at__gt=date_utils.timestamp2datetime(ts))

這段代碼很簡單,主要就是將前臺(tái)傳遞過來的時(shí)間戳轉(zhuǎn)換成 DateTime 類型的數(shù)據(jù),然后利用created_at__gt來過濾,就是大于這個(gè)時(shí)間點(diǎn)的就可以。然后問題來了,查詢出來的數(shù)據(jù)始終包含了上一頁最后一條數(shù)據(jù),感覺很奇怪,我這里明明用的是gt而不是gte,怎么會(huì)重復(fù)這條數(shù)據(jù)呢。

于是,我們把上一頁最后一條數(shù)據(jù)的 created_at 字段打印出來和傳遞過來的時(shí)間戳進(jìn)行對(duì)比下:

>>> task = Task.objects.get(pk=2)
>>> task.created_at
datetime.datetime(2019, 1, 7, 10, 54, 1, 343136)

然后將時(shí)間戳轉(zhuǎn)換成 DateTime 類型的數(shù)據(jù):

>>> ts = int(1546829641000/1000)
>>> date_utils.timestamp2datetime(ts)
datetime.datetime(2019, 1, 7, 10, 54, 1)

現(xiàn)在看到區(qū)別沒有,從數(shù)據(jù)庫中查詢出來的 created_at 字段的值包含了一個(gè)微秒,就是后面的 343136,而時(shí)間戳轉(zhuǎn)換成 DateTime 類型的值是不包含這個(gè)微秒值的,所以我們上面查詢的使用created_at__gt來進(jìn)行過濾很顯然 created_at 的值是大于下面的值的,因?yàn)槎嗔艘粋€(gè)微秒,所以就造成了數(shù)據(jù)重復(fù)了,終于破案了。

解決方法

那么要怎么解決這個(gè)問題呢?當(dāng)然我們可以直接在數(shù)據(jù)庫中就保存一個(gè)時(shí)間戳的字段,用這個(gè)字段直接來進(jìn)行查詢過濾,肯定是可以解決這個(gè)問題的。

如果就用現(xiàn)在的 created_at 這個(gè) DateTimeField 類型呢?如果保存的數(shù)據(jù)沒有這個(gè)微秒是不是也可以解決這個(gè)問題???

我們可以去查看下源碼為什么 DateTimeField 類型的數(shù)據(jù)會(huì)包含微秒,下面是django/db/backends/mysql/base.py文件中的部分代碼說明:

class DatabaseWrapper(BaseDatabaseWrapper):
 vendor = 'mysql'
 # This dictionary maps Field objects to their associated MySQL column
 # types, as strings. Column-type strings can contain format strings; they'll
 # be interpolated against the values of Field.__dict__ before being output.
 # If a column type is set to None, it won't be included in the output.
 _data_types = {
 'AutoField': 'integer AUTO_INCREMENT',
 'BinaryField': 'longblob',
 'BooleanField': 'bool',
 'CharField': 'varchar(%(max_length)s)',
 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
 'DateField': 'date',
 'DateTimeField': 'datetime',
 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
 'DurationField': 'bigint',
 'FileField': 'varchar(%(max_length)s)',
 'FilePathField': 'varchar(%(max_length)s)',
 'FloatField': 'double precision',
 'IntegerField': 'integer',
 'BigIntegerField': 'bigint',
 'IPAddressField': 'char(15)',
 'GenericIPAddressField': 'char(39)',
 'NullBooleanField': 'bool',
 'OneToOneField': 'integer',
 'PositiveIntegerField': 'integer UNSIGNED',
 'PositiveSmallIntegerField': 'smallint UNSIGNED',
 'SlugField': 'varchar(%(max_length)s)',
 'SmallIntegerField': 'smallint',
 'TextField': 'longtext',
 'TimeField': 'time',
 'UUIDField': 'char(32)',
 }

 @cached_property
 def data_types(self):
 if self.features.supports_microsecond_precision:
  return dict(self._data_types, DateTimeField='datetime(6)', TimeField='time(6)')
 else:
  return self._data_types

 # ... further class methods

上面的 data_types 方法中在進(jìn)行 MySQL 版本檢查,屬性supports_microsecond_precision來自于文件django/db/backends/mysql/features.py:

class DatabaseFeatures(BaseDatabaseFeatures):
 # ... properties and methods

 def supports_microsecond_precision(self):
 # See https://github.com/farcepest/MySQLdb1/issues/24 for the reason
 # about requiring MySQLdb 1.2.5
 return self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5)

從上面代碼可以看出如果使用的 MySQL 大于等于 5.6.4 版本,屬性DateTimeField會(huì)被映射成為數(shù)據(jù)庫中的datetime(6),所以保存的數(shù)據(jù)就包含了微秒。

在 Django 中暫時(shí)沒有發(fā)現(xiàn)可以針對(duì)改配置進(jìn)行設(shè)置的方法,所以我們要想保存的數(shù)據(jù)不包含微秒,我們這里則可以將上面的data_types屬性進(jìn)行覆蓋即可:

from django.db.backends.mysql.base import DatabaseWrapper

DatabaseWrapper.data_types = DatabaseWrapper._data_types

將上面的代碼放置在合適的地方,比如models.py或者_(dá)_init__.py或者其他地方,當(dāng)我們運(yùn)行 migrations 命令來創(chuàng)建 DateTimeField 列的時(shí)候?qū)?yīng)在數(shù)據(jù)庫中的字段就被隱射成為了datetime,而不是datetime(6),即使你用的是 5.6.4 版本以上的數(shù)據(jù)庫。

當(dāng)然要立即解決當(dāng)前的問題,只需要更改下數(shù)據(jù)庫中的 created_at 字段的類型即可:

mysql> ALTER TABLE `task` CHANGE COLUMN `created_at` `created_at` datetime NOT NULL;
Query OK, 156 rows affected (0.14 sec)
Records: 156 Duplicates: 0 Warnings: 0

這樣數(shù)據(jù)重復(fù)的 BUG 就解決了。

以上是“怎么在Django中添加沒有微秒的 DateTimeField屬性詳解”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI