Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM query against data month, day, year?

So, I know I can use __lte and __gte filters on object dates using the Django ORM as so:

events = Event.objects.all().order_by('start_date').filter(
    start_date__lte=_day, end_date__gte=_day
)       

I can also query against date components:

events = Event.objects.all().order_by('start_date').filter(
    start_date__day=_day.day, end_date__day=_day.day
)       

but what I'm trying to figure out is can I query against specific parts of the date AND also use the gte and lte operators, such as the following attempt that doesn't work:

events = Event.objects.all().order_by('start_date').filter(
    start_date__day__lte=8, end_date__day__gte=_day
)   
like image 551
shawnwall Avatar asked Feb 25 '26 04:02

shawnwall


1 Answers

Short answer: no, you can't.

Long(er) answer:

In this case I'd create a method on the manager, and use either .extra(where='...') (which would probably require DB-specific SQL code) or a combination of models.Q objects on the Event queryset.

class EventManager(models.Manager):
    def day_range(self, start, end):
        qs = self.get_queryset()
        qs = qs.extra(where=["day(start_date) < %s and day(end_date) > %s"],
                      params=[start, end])
        return qs

Edited: the where arg had to be a sequence.

like image 67
rewritten Avatar answered Feb 27 '26 18:02

rewritten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!