문제

Can I modify the following query to make it more concise way using Django ORM?

queryset.filter((Q(from_date__lte=from_date) & \
                 Q(to_date__gt=from_date)) | \
                (Q(from_date__lte=to_date) & 
                 Q(to_date__gt=to_date)))

Here are some examples:

"from_date": "2014-05-11 08:00:00", 
"to_date": "2014-05-11 10:00:00",

"from_date": "2014-05-12 12:00:00", 
"to_date": "2014-05-12 15:00:00",

These are the dates in the database

If you submit

fromDate=2014-05-11 08:00:00
toDate=2014-05-11 13:00:00

should give me only the first date

"from_date": "2014-05-11 08:00:00", 
"to_date": "2014-05-11 10:00:00",

Here again, should give me only the first result

fromDate=2014-05-11 09:00:00
toDate=2014-05-11 13:00:00

If I submit the following date

fromDate=2014-05-11 07:00:00
toDate=2014-05-11 09:00:00

Again, only the first result should be taken

If you do so you can get both results

fromDate=2014-05-11 09:00:00
toDate=2014-05-12 13:00:00

I hope you understand what's the idea.

The query should remain the same logic!

도움이 되었습니까?

해결책

queryset.filter(to_date__gt=from_date, from_date__lt=to_date)

That is, to be returned the event must end after the new event starts and must start before the new event ends. Anything that ends before the new from_date is not returned, neither is anything that doesn't start until after it ends.

That does not precisely match your original query, but it does match the behavior described in the comments for when there's a record in the database that is entirely within the range set by the new dates.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top