Get queryset date rage

I have 2 fields for start date and end date. How to get a rows that falls between the start and end dates.

That my model

class Shop(models.Model):
    time_begin = models.TimeField(max_length=255,
                              verbose_name=u'Время начала работы')
    time_end = models.TimeField(max_length=255,
                            verbose_name=u'Время окончания работы')

Upvotes: 0

Views: 676

Answers (2)

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

You can use django's filter with datetime.time objects:

import datetime
shops = Shop.objects.filter(time_begin__gte=datetime.time(10, 0, 0),
                              time_end__lte=datetime.time(22, 0, 0))

Same (__gte & __lte) can also work for DateTime or Date fields. However, if you're using Django 2.2+ you can use the appropriate built-in filters __time, __hour, __minute or __second as per need.

Upvotes: 2

Jessie
Jessie

Reputation: 2475

You can use the __lt and __gt filters to target dates in between both.

Shop.objects.filter(time_begin__gte=<date>, time_end__lt=<date>)

If you're using DateField and want to include the end date, use lte, otherwise use lt.

Upvotes: 1

Related Questions