什么是模型中django dateTime的正确格式?

问题描述 投票:0回答:1

我是django的新手,我正在创建我的第一个项目。我创建了一个应用程序,其中模型我定义了一个postgres数据时间字段,但是当运行migrate命令时,我总是得到该字段的错误。

我在models.py的datetime字段中使用了以下值,但没有任何反应

created=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(default='', blank=True, null=True)
created=models.DateTimeField(blank=True, null=True)
created=models.DateTimeField(default='0000-00-00 00:00:00', blank=True, null=True)

在我的settings.py中

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

我的models.py

from django.db import models
from django.utils import timezone
# from django.contrib.auth.models import User

# Create your models here.
class Operator(models.Model):
operator_code=models.CharField(unique=True, max_length=20)
operator_name=models.CharField(max_length=60)
operator_type=models.CharField(max_length=60)
short_code=models.CharField(max_length=60)
apiworld_code=models.CharField(max_length=20)
apiworld_operatortype=models.CharField(max_length=20)
active_api_id=models.IntegerField(default=1)
ospl_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2)
apiworld_commission=models.DecimalField(default=0.00, max_digits=11, decimal_places=2)
image=models.CharField(max_length=100)
status=models.SmallIntegerField(default=1)
updated=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(default=timezone.now)

def __str__(self):
    return self.operator_code

当我运行'python manage.py migrate'时,我得到以下错误如何删除它

'django.core.exceptions.ValidationError:[“''0000-00-00 00:00:00'值的格式正确(YYYY-MM-DD HH:MM [:ss [.uuuuuu]] [TZ])但是这是一个无效的日期/时间。“]'

python django postgresql pycharm
1个回答
3
投票

要回答你的问题,Django中DateTimeField的格式是在默认设置中定义的,如下所示:https://docs.djangoproject.com/en/2.2/ref/settings/#datetime-input-formats

在这个时间点它默认为以下,但显然可能会有所不同,具体取决于您使用的Django版本:

[
    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
    '%Y-%m-%d',              # '2006-10-25'
    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
    '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
    '%m/%d/%Y',              # '10/25/2006'
    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
    '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
    '%m/%d/%y %H:%M',        # '10/25/06 14:30'
    '%m/%d/%y',              # '10/25/06'
]

但是,看看你的代码,我想你想知道“在Django中创建默认DateTime值的正确方法是什么”的答案。

答案取决于你想要的默认值。如果你想要价值是null那么这很容易。

myfield = models.DateTimeField(null=True, blank=True, default=None)

如果您正在尝试创建created_atupdated_at字段,那么您希望分别使用auto_now_addauto_now kwargs,这将自动填充模型实例创建和更新时的字段。

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
© www.soinside.com 2019 - 2024. All rights reserved.