0

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.

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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()
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.