Home > Back-end >  Is there a way to add the date field in models in a "from to" pattern for billing periods
Is there a way to add the date field in models in a "from to" pattern for billing periods

Time:10-15

I am trying to add a billing period in the invoices that I am generating. Currently my model contains two seperate date fields, one that stores the start date of the billing period and the other stores the end date of the billing period. The model looks as below


class Bill(models.Model):
    
    billing_period_start = models.DateField(null=True, blank=True)
    
    billing_period_end = models.DateField(null=True, blank=True)   

Question :

Is there a way to add the two seperate date fields in a same model field so that I can get a
from "DateField" to "DateField" (For example, From 2022-09-01 to 2022-09-30) pattern in the admin pannel and have the billing period in a single field.

CodePudding user response:

If you use PostgreSQL you can use DateRangeField https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/fields/#daterangefield Otherwise you can implement custom field yourself.

CodePudding user response:

You can use the DateRangeField available for postgres.

from django.contrib.postgres.fields import DateRangeField

class Bill(models.Model):
    date_range = DateRangeField()

You can assign a value to this field directly with a tuple:

Create a range from 2021-01-01 to 2021-04-01
bill.date_range = ('2021-01-01', '2021-04-01')

You can also create the range explicitly with DateTimeTZRange (that's what you will get from the database anyway):

from psycopg2.extras import DateTimeTZRange
instance.validity_range = DateTimeTZRange(lower='2021-01-01', upper='2021-03-31')

See here for more about this field

  • Related