[Django]-Django get foreign key object inside Queryset

5👍

It sounds like you’re looking for select_related().

qs = SubSubEvent.objects \
    .select_related('sub_event__event') \
    .filter(sub_event__event__cur_datetime__range=[from_date, to_date])

You can then access the related SubEvent and Event resources without hitting the database.

sub_sub_event = qs[0]
sub_event = sub_sub_event.sub_event    # doesn't hit the database
event = sub_sub_event.sub_event.event  # doesn't hit the database
👤Sherpa

Leave a comment