Mark Anthony Libres
Mark Anthony Libres

Reputation: 1074

Filter dates between two dates in Django Orm

I've have this model

class Batch(models.Model):
    id = models.AutoField(primary_key=True);
    start_date = models.DateField(null=False, blank=False, default=date.today);
    end_date = models.DateField(null=False, blank=False, default=date.today);
    description = models.TextField(blank=True);
    name = models.CharField(max_length=22, null=False, blank=False, default=None);
    date_created = models.DateField(verbose_name='Date created', default=date.today, editable=False);
    school = models.ForeignKey(User,on_delete=models.CASCADE, default=None,blank=False,null=False);

I need to filter "start_date" and "end_date" to check if a specified date is in between. Something like this

SELECT * FROM philiri.group_batch where (Date("04-11-1997") BETWEEN start_date and end_date)

Im try to use __range, __lte, __gte , __lt, __gt but it doesn't fit this problem.

Upvotes: 0

Views: 904

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477685

You can first inject the data through annotation, and then filter with this:

from django.db.models import DateField, F, Value
from datetime import date

Batch.object.annotate(
    mydate=Value(date(1997, 11, 4), output_field=DateField())
).filter(
    mydate__range=(F('start_date'), F('end_date'))
)

but it might be simpler to simply filter on the given date:

from datetime import date

Batch.object.filter(
    start_date__gte=date(1997, 11, 4),
    end_date__lte=date(1997, 11, 4)
)

Upvotes: 1

Related Questions