N
N
Nikita Kotenko2016-01-23 02:47:49
Django
Nikita Kotenko, 2016-01-23 02:47:49

How to store a range of dates in the datetime.date format from two models.DateField fields in a DB field?

There is a model:

class Reservation(models.Model):
   order_date = models.DateTimeField(auto_now_add=True, verbose_name='Создана')
   #...
   checkin = models.DateField(verbose_name='Дата заезда')
   checkout = models.DateField(verbose_name='Дата выезда')
   days = ???

How to store in days a list of days from checkin to checkout in datetime.date format? And where is it done anyway? Directly in the class, or by a method inside the class? Or even a separate function in a separate application in a parallel world?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikita Konin, 2016-01-23
@n_angelo

In my application, I simply calculate the difference between timestamps using a method.
In your case it will be something like this:

def get_date_diff(self):
    return (self.checkout - self.checkin).days

Or, if you need a list with datetime.date objects:
def get_date_diff(self):
    return [self.checkout + datetime.timedelta(i) for i in range((self.checkout - self.checkin).days)]

V
Vladimir, 2016-01-23
@vintello

if the list of days is necessary - make the subordinate table with the list of dates which enter into an interval. dates can be generated by signal .
If you just need to calculate how many days - use advice from Nikita Konin
If nothing fits - formulate your question again, because it is not very clear from it what you want to end up with

A
Artem Klimenko, 2016-01-23
@aklim007

If you have PostgreSQl and not the old djanga, then everything is simple:
https://docs.djangoproject.com/es/1.9/ref/contrib/...

from django.contrib.postgres.fields import ArrayField
from django.db import models

class ArrayFieldTest(models.Model):
    days = ArrayField(base_field=models.DateField(), default=list)

>>> from test.models import ArrayFieldTest
>>> from django.utils import timezone
>>> from dateutil.relativedelta import relativedelta
>>> date_list = [timezone.now().date(), timezone.now().date() + relativedelta(days=1)]
>>> date_list
[datetime.date(2016, 1, 23), datetime.date(2016, 1, 24)]
>>> ArrayFieldTest(days=date_list).save()
>>> ArrayFieldTest.objects.all().first().days
[datetime.date(2016, 1, 23), datetime.date(2016, 1, 24)]
>>> ArrayFieldTest().save()
>>> ArrayFieldTest.objects.all().last().days
[]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question