Reputation: 694
I want to have my queryset of Card
model annotated with new field called available_on, which should be calculated as closest date in future of relative Booking
model's field removal_date
. It should consider only dates in future, how can I filter out removal_date dates that are in the past? What I have now is this.
def with_available_on(self):
qs = self.annotate(available_on=Case(
When(
bookings_count__gt=0,
slots_available__lt=1,
then=Min('bookings__removal_date')),
default=None
)
)
return qs
Also I want it to be calculated on database side if possible for performance purposes. Thanks
Upvotes: 1
Views: 311
Reputation: 476584
You can use the filter=…
parameter [Django-doc] to filter the objects over which you span the aggregate in the Min
aggregate [Django-doc]:
from django.db.models import Q
from django.db.models.functions import Now
def with_available_on(self):
qs = self.annotate(available_on=Case(
When(
bookings_count__gt=0, slots_available__lt=1,
then=Min(
'bookings__removal_date',
filter=Q(bookings__remval_date__gte=Now())
)
),
default=None)
)
return qs
Upvotes: 2