Reputation:
I have the following two queries in my Django view:
current_events = user.ambassador_profile.first().events.all().filter(end_date__gt=now)
past_events = user.ambassador_profile.first().events.all().filter(end_date__lt=now)
I am not sure, but is there a better way to combine these. Currently, I am doing two queries in my database and I feel like that's wrong.
Upvotes: 0
Views: 49
Reputation: 32244
You can use annotate
and Case
to add an attribute to each object that says if it is "current" or not
user.ambassador_profile.first().events.all().annotate(
current=Case(
When(end_date__gt=now, then=Value(True)),
default=Value(False),
output_field=BooleanField()
)
)
Upvotes: 1
Reputation: 47354
If you need to filter all events except end_date=now
you can use exclude
:
all_events = user.ambassador_profile.first().events.exclude(end_date=now)
Upvotes: 1