Using Django, I want to find all of the published events after today, but only from the nearest month containing events
I have an event object which has from_date
as a field which represents when the event starts. What I want to do is to find the nearest event, and then find the next upcoming events that are still within the month. Here are the two queries I have so far, is there a way to combine them?
today = datetime.date.today()
date = Event.objects.filter(
status='P', # Published status
pub_date__lte=today, # Published after today, or today
from_date__gte=today, # Starting next
).order_by('from_date').only('from_date')[:1][0].from_date
events = Event.objects.filter(
# Published after today, with a published status, and start today or later
pub_date__lte=today,
f开发者_JAVA技巧rom_date__gte=today,
status='P',
# We're only going to show one month at a time.
from_date__month=date.month,
from_date__year=date.year,
)
I think what you're already doing is actually pretty efficient. Django's query mechanism should collapse those into two SQL queries, one for each filter.
Jamming everything into a single SQL query doesn't always make it more efficient.
精彩评论