Home > Blockchain >  Django models.DateTimeField, how to store the value without seconds?
Django models.DateTimeField, how to store the value without seconds?

Time:10-30

I have this model

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', )

How can I store appointment_date value without seconds in the DB? Right now the value is like this 2021-11-05 17:30:43 I'd like to store it as 2021-11-05 17:30

That's because otherwise unique_together is basically useless for what I need.

CodePudding user response:

I wrote an article about constructing variants of a DateTimeField that will truncate to a week, month, minute, etc.

In this case we can make a MinuteDateTimeField with:

# 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)

Then you can use this MinuteDateTimeField with:

# app_name/models.py

from app_name.fields import MinuteDateTimeField

class Appointments(models.Model):
    # ⋮
    appointment_date = MinuteDateTimeField(null=True, blank=True)
  • Related