【问题标题】:Django ORM return None for not null columns对于非空列,Django ORM 返回 None
【发布时间】:2016-05-16 08:57:14
【问题描述】:

我有以下 django 模型

class CalculatedResults(models.Model):
 id = models.IntegerField(primary_key=True)
 tmstamp = models.DateTimeField()
 latitude = models.FloatField()
 longitude = models.FloatField()
 magnitude = models.FloatField()
 origin_time = models.DateTimeField()
 actioncode = models.IntegerField(db_column='actionCode', blank=True, null=True) # Field name made lowercase.
 class Meta:
     managed = False
     db_table = 'calculated_results'
     verbose_name = 'Calculated Result'
     verbose_name_plural = 'Calculated Results'

相关的mysql表是:

CREATE TABLE IF NOT EXISTS `calculated_results` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tmstamp` timestamp(5) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `latitude` double NOT NULL,
  `longitude` double NOT NULL,
  `magnitude` double NOT NULL DEFAULT '0',
  `origin_time` timestamp(5) NOT NULL DEFAULT '0000-00-00 00:00:00.00000',
  `actionCode` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `tmstamp_index` (`tmstamp`),
  KEY `origin_time_index` (`origin_time`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=814 ;

当我尝试使用以下代码使用python manage.py shell 从表中检索数据时,

form eew_main.models import CalculatedResults
a = CalculatedResults.objects.all().order_by('-id')[:1]

我得到Nonetmstamporigin_time 但据我调查这个问题,以下sql 查询被发送到mysql

SELECT  `calculated_results`.`id` ,  `calculated_results`.`tmstamp` ,  `calculated_results`.`latitude` ,  `calculated_results`.`longitude` ,  `calculated_results`.`magnitude` , `calculated_results`.`origin_time` ,  `calculated_results`.`actionCode` 
FROM  `calculated_results` 
ORDER BY  `calculated_results`.`id` DESC 
LIMIT 1

当我使用 django 使用的相同 mysql 用户在 mysql 上尝试时,我得到了所有值。

所以请帮助我找到一种方法来调查和解决这个问题。

谢谢!

【问题讨论】:

  • 是所有日期都返回None,还是只返回日期为零的'0000-00-00 00:00:00.00000'
  • @Alasdair 它为所有值返回 null 而不仅仅是零日期
  • @abyz 为什么这个模型管理状态是假的?它禁止 django 为该表创建迁移 managed in model
  • @shalbafzadeh 因为它是由另一个 c++ 应用程序创建并由它管理的表,因此管理状态为 False

标签: python mysql django django-models


【解决方案1】:

似乎您的表是在 Django 之外创建的。 Django 的 models.DateTimeField 将在 MySQL 中合成为 datetime 字段而不是 timestamp

检查this answer 以获取类似于DateTimeField 在SQL 级别使用timestamp 的实现。

【讨论】:

  • 感谢您的帮助,但日期是由其他人生成的,仅由 django 读取。在生产服务器中会发生,但在开发服务器中没有任何问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2022-01-13
  • 2020-08-22
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多