django - Django models.DateTimeField,如何在没有秒的情况下存储值?
问题描述
我有这个模型
class Appointments(models.Model):
options = (
('waiting', 'In Attesa'),
('confirmed', 'Confermato'),
('closed', 'Chiuso'),
)
duration = (
('15', '15 minuti'),
('20', '20 minuti'),
('30', '30 minuti'),
('40', '40 minuti'),
)
date = models.DateTimeField(default=timezone.now)
patient_first_name = models.CharField(max_length=250)
patient_last_name = models.CharField(max_length=250)
patient_email = models.EmailField(_('email address'))
patient_phone = models.CharField(max_length=250)
doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT)
room = models.ForeignKey(Room, on_delete=models.PROTECT, default=1)
status = models.CharField(max_length=10, choices=options, default='waiting')
message = models.TextField(null=True, blank=True)
notes = models.TextField(null=True, blank=True)
appointment_date = models.DateTimeField(null=True, blank=True)
duration = models.CharField(max_length=10, choices=duration, default='15')
class Meta:
ordering = ('-date', )
unique_together = ('appointment_date', 'room', )
如何appointment_date
在数据库中存储价值而不需要几秒钟?现在的值是这样的,2021-11-05 17:30:43
我想将它存储为2021-11-05 17:30
那是因为否则unique_together
对于我需要的东西基本上是无用的。
解决方案
我写了一篇关于构建 a 的变体的文章DateTimeField
,它将截断为一周、一个月、分钟等。
在这种情况下,我们可以MinuteDateTimeField
使用:
# app_name/fields.py
from datetime import timedelta
from django.db.models import DateTimeField
class DateTruncMixin:
def truncate_date(self, dt):
return dt
def to_python(self, value):
value = super().to_python(value)
if value is not None:
return self.truncate_date(value)
return value
class MinuteDateTimeField(DateTruncMixin, DateTimeField):
def truncate_date(self, dt):
return dt.replace(second=0, microsecond=0)
然后你可以使用它MinuteDateTimeField
:
# app_name/models.py
from app_name.fields import MinuteDateTimeField
class Appointments(models.Model):
# ⋮
appointment_date = MinuteDateTimeField(null=True, blank=True)
推荐阅读
- dom - 来自特定服务器的特定 URL 上的 JSoup 超时
- data-structures - 如何最好地实现 itoa 和 atoi?
- javascript - 主题标签和单词的边界正则表达式
- c++ - 控制到达非空函数重载运算符 [] 的末尾;
- sql-server - 批处理文件来解析字符串的文本文件,该字符串将在返回 true 时执行 SQL 语句
- dart - 为什么我们在 Flutter 中需要 Statefulwidget 中的 State 方法?
- jquery - 为 jquery mouseleave 工具提示悬停添加延迟
- javascript - 在不使用 flexbox 的情况下对齐项目的顶部和底部
- javascript - 从 SuiteScript 的下拉菜单中选择一个选项后,如何使文本框出现?
- r - 如何在具有不同长度元素的列表上选择行并使用应用功能