日期验证错误尝试从sqllite迁移到django中的mssql时发生。

huangapple go评论144阅读模式
英文:

Date Validatind Error When Trying To Migrate From sqllite to mssql in django

问题

这个错误是由于数据库迁移中的一个日期时间字段的默认值格式不正确引起的。错误信息表明,““” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.”,即日期时间字段的默认值必须符合“YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]”的格式。

要解决这个问题,你需要检查你的模型中所有日期时间字段的默认值,确保它们都符合正确的日期时间格式。在你的代码中搜索“expiration_date”字段,然后确保它的默认值设置为正确的格式,例如:“2023-09-23 10:00:00”。

这样做后,运行数据库迁移命令,应该就不会再出现这个错误了。如果你需要更多帮助,请提供涉及日期时间字段的具体代码部分,以便我可以为你提供更详细的指导。

英文:
from django.db import models
from tinymce import models as tinymce_models
from django.core.exceptions import ValidationError
from django.utils import timezone
# Create your models here.
class Role(models.Model):
roleName    = models.CharField(max_length=200)
active      =models.BooleanField(default=True)
createdBy   =models.CharField(max_length=200)
modifiedBy  =models.CharField(max_length=200)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Role"
def __str__(self):
return self.roleName
class CMSUser(models.Model):
fullName    =models.CharField(max_length=200)
email       =models.CharField(max_length=200)
password    =models.CharField(max_length=200)
active      =models.BooleanField(default=True)
createdBy   =models.CharField(max_length=200)
modifiedBy  =models.CharField(max_length=200)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="User"
def _str_(self):
return self.fullName  
class Campus(models.Model):
campusName = models.CharField(max_length=200,unique=True)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Campus"
def __str__(self):
return self.campusName 
class Group(models.Model):
groupName   =models.CharField(max_length=200)
active      =models.BooleanField(default=True)
createdBy   =models.CharField(max_length=200)
modifiedBy  =models.CharField(max_length=200)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Group"
def __str__(self):
return self.groupName
class Menu(models.Model):
menuName    =models.CharField(max_length=200)
active      =models.BooleanField(default=True)
createdBy   =models.CharField(max_length=200)
modifiedBy  =models.CharField(max_length=200)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Menu"
def _str_(self):
return self.menuName
class Content(models.Model):
contentTitle    =models.CharField(max_length=200)
contentImage    =models.ImageField(upload_to='upload/content/')
contentData     =tinymce_models.HTMLField()
menuID          =models.ForeignKey(Menu, on_delete=models.CASCADE)
active          =models.BooleanField(default=True)
createdBy       =models.CharField(max_length=200)
modifiedBy      =models.CharField(max_length=200)
createdat       =models.DateTimeField(db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat       =models.DateTimeField(db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Content"
def _str_(self):
return self.contentTitle 
class UserRole(models.Model):
roleID = models.ForeignKey(Role, on_delete=models.CASCADE)
cmUserID = models.ForeignKey(CMSUser, on_delete=models.CASCADE)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="UserRole"
class UserGroup(models.Model):
groupID = models.ForeignKey(Group, on_delete=models.CASCADE)
cmUserID = models.ForeignKey(CMSUser, on_delete=models.CASCADE)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="UserGroup"
class GroupMenu(models.Model):
groupID = models.ForeignKey(Group, on_delete=models.CASCADE)
menuID = models.ForeignKey(Menu, on_delete=models.CASCADE)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="GroupMenu"
class ParentDepartment(models.Model):
departmentName = models.CharField(max_length=200,unique=True)
departmentShortName = models.CharField(max_length=200,unique=True)
campusId = models.ForeignKey(Campus, on_delete=models.CASCADE)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="ParentDepartment"
def __str__(self):
return self.departmentName
class ChildDepartment(models.Model):
departmentName = models.CharField(max_length=200,unique=True)
departmentShortName = models.CharField(max_length=200,unique=True)
parentDepartment = models.ForeignKey(ParentDepartment, on_delete=models.CASCADE)
deptDescription =tinymce_models.HTMLField(null=False, blank=False,default='N/A')
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="ChildDepartment"
def __str__(self):
return self.departmentName 
class Jobs(models.Model):
jobTitle       =models.CharField(max_length=200)
# jobImage    =models.ImageField(upload_to='upload/jobs/',blank=False, null=False, default='')
jobDescription =tinymce_models.HTMLField()
jobActive      =models.BooleanField(default=True)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')
class Meta:
verbose_name_plural="Jobs"
def _str_(self):
return self.jobTitle 
def clean(self):
if self.expiration_date <= timezone.now():
raise ValidationError("Expiration date must be greater than the current date.")
def save(self, *args, **kwargs):
self.clean()  # Run the clean method before saving
super().save(*args, **kwargs)
class NewUpdates(models.Model):
newsTitle       =models.CharField(max_length=200)
newsContent =tinymce_models.HTMLField()
newsActive      =models.BooleanField(default=True)
titleImage = models.ImageField(upload_to='upload/newupdates/')
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')
class Meta:
verbose_name_plural="NewsUpdates"
def _str_(self):
return self.newsTitle 
def clean(self):
if self.expiration_date <= timezone.now():
raise ValidationError("Expiration date must be greater than the current date.")
def save(self, *args, **kwargs):
self.clean()  # Run the clean method before saving
super().save(*args, **kwargs)
class StudentNoticeBoard(models.Model):
# contents =tinymce_models.HTMLField()
Image    =models.ImageField(upload_to='upload/noticeboard/',blank=False, null=False, default='')
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')
class Meta:
verbose_name_plural="StudentNoticeBoard"
def clean(self):
if self.expiration_date <= timezone.now():
raise ValidationError("Expiration date must be greater than the current date.")
def save(self, *args, **kwargs):
self.clean()  # Run the clean method before saving
super().save(*args, **kwargs)
class Events(models.Model):
# contents =tinymce_models.HTMLField()
Image    =models.ImageField(upload_to='upload/events/',blank=False, null=False, default='')
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')
class Meta:
verbose_name_plural="Events"
def clean(self):
if self.expiration_date <= timezone.now():
raise ValidationError("Expiration date must be greater than the current date.")
def save(self, *args, **kwargs):
self.clean()  # Run the clean method before saving
super().save(*args, **kwargs)
class Tender(models.Model):
# contents =tinymce_models.HTMLField()
Image    =models.ImageField(upload_to='upload/tender/',blank=False, null=False, default='')
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')
class Meta:
verbose_name_plural="Tender"
def clean(self):
if self.expiration_date <= timezone.now():
raise ValidationError("Expiration date must be greater than the current date.")
def save(self, *args, **kwargs):
self.clean()  # Run the clean method before saving
super().save(*args, **kwargs)
class CampusGroups(models.Model):
campus =models.ForeignKey(Campus, on_delete=models.CASCADE)
group =models.ForeignKey(Group, on_delete=models.CASCADE)
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class FacultyProfiles(models.Model):
name       =models.CharField(max_length=200)
Image    =models.ImageField(upload_to='upload/faculty/')
designation= models.CharField(max_length=200)
jouralPublications= models.IntegerField()
conferencePublications= models.IntegerField()
address       =models.CharField(max_length=200)
phone = models.CharField(max_length=200)
mobile = models.CharField(max_length=200)
fax = models.CharField(max_length=200)
email = models.CharField(max_length=200)
description =tinymce_models.HTMLField()
createdat = models.DateTimeField(
db_column='createdAt', blank=True, null=True, auto_now_add=True)
updatedat = models.DateTimeField(
db_column='updatedAt', blank=True, null=True, auto_now=True)
class Meta:
verbose_name_plural="Faculty"
def _str_(self):
return self.name 

Above is the code for my model. The following is the error that I am facing.


Operations to perform:
Apply all migrations: MasterUser, admin, auth, contenttypes, sessions
Running migrations:
Applying MasterUser.0010_alter_events_expiration_date_and_more...Traceback (most recent call last):
File "C:\Users\Qamar\Desktop\ContentManagementSystem\manage.py", line 22, in <module>
main()
File "C:\Users\Qamar\Desktop\ContentManagementSystem\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards     
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\operations\fields.py", line 244, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\schema.py", line 594, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\mssql\schema.py", line 461, in _alter_field
new_default = self.effective_default(new_field)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\schema.py", line 310, in effective_default        
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save       
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1427, in get_db_prep_value     
value = self.get_prep_value(value)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1406, in get_prep_value        
value = super().get_prep_value(value)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value        
return self.to_python(value)
File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

help me in resolving this problem

答案1

得分: 1

在您的事件模型中,这行代码存在问题...

expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

默认值是一个空字符串。然而,blank=False 明确禁止在字段中保存空字符串。在迁移中,您正在复制记录,实际上是在其他地方创建它们,因此它们的字段限制在保存时生效。在这里,您在复制没有过期日期的记录时违反了保存要求。

目前,您的字段不允许为空(例如,表单中的空字段)或为空(数据库中的空字段)。为了在迁移期间处理当前没有为其创建条目的记录,您可以:

  • 您可以在迁移期间将 blank=True

  • 您可以将默认值更改为 None 并在迁移期间设置 null=True

  • 或者您可以将默认值设置为一个明确的时间,例如 datetime.now(),或者按错误消息中的格式设置为字符串:YYYY-MM-DD HH:MM

英文:

In your Events model, this line has a problem...

expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

The default value is an empty string. However, blank=False explicitly disallows saving with an empty string in the field. In a migration, you're copying over records, which is basically creating them new elsewhere, so their field limitations apply when they get saved. Here you are breaking your saving requirements when copying records with no expiration_date.

Currently your field is not allowed to be blank (eg, an empty field on a form) or Null (an empty field in a database). To handle the records that don't currently have an entry for them during a migration you could:

  • You could set blank=True for the duration of your migration

  • You could change the default to None and set null=True
    during the migration

  • Or you could set the default to be an explicit time, like
    datetime.now(), or a string as formatted in the error message: YYYY-MM-DD HH:MM

huangapple
  • 本文由 发表于 2023年6月13日 09:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定