我是 django 的新手,我正在创建我的第一个项目。我创建了一个应用程序,我在其中的模型中定义了一个 postgres 数据时间字段,但在运行迁移命令时我总是收到此字段的错误消息。
我在 models.py 中为日期时间字段使用了以下值,但没有任何反应
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
我的模型.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 ]) 但这是一个无效的日期/时间。"]'
最佳答案
为了回答您的问题,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_at
和 updated_at
字段,那么您需要使用 auto_now_add
和 auto_now
kwargs 分别会在创建和更新模型实例时自动填写字段。
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
关于python - 模型中 django dateTime 的正确格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55827713/