[Django]-Django model filtering with F and Q expressions

5👍

from datetime import timedelta

Event.objects.filter(end__gt=F('start') + timedelta(days=9))

Documentation has example.

UPDATE:

Events, that span more than 9 days AND (start later than Monday OR end sooner than Sunday), ordered by start.

(Event.objects
 .filter(end__gt=F('start') + timedelta(days=9),
         Q(start__gte=monday) | Q(end__lte=sunday))
 .order_by('start'))
👤f43d65

0👍

Just the warning to @https://stackoverflow.com/users/4907653/f43d65
‘s answer, that last query lookups with Q objects might be invalid.

Reference to docs

Lookup functions can mix the use of Q objects and keyword arguments. All arguments provided to a lookup function (be they keyword arguments or Q objects) are “AND”ed together. However, if a Q object is provided, it must precede the definition of any keyword arguments. For example:

Poll.objects.get(
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
question__startswith='Who',)

… would be a valid query, equivalent to the previous example; but:

# INVALID QUERY
Poll.objects.get(
    question__startswith='Who',
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

… would not be valid.

Leave a comment