首页 > 解决方案 > 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对于我需要的东西基本上是无用的。

标签: djangodatetimedjango-modelsdjango-rest-framework

解决方案


我写了一篇关于构建 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)

推荐阅读