开发者

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_d开发者_JS百科ate').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
)   


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜