Atrus
Atrus

Reputation: 798

Getting all foreign keys from a QuerySet

I have two models, Story and FollowUp. FollowUp can have a foreign key of Story. Story has a foreign key of User.

I can get all Story that are associated with a User with user.story_set.all(). I would like to, without iterating through the queryset, be able to get all FollowUps associated with all the Storys.

I had initially tried user.story_set.all().followup_set.all(), but that does not work.

How can I accomplish this?

Upvotes: 1

Views: 2207

Answers (2)

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

A more concise approach is:

FollowUp.objects.filter(story__user=user)

Upvotes: 0

Thomas Orozco
Thomas Orozco

Reputation: 55303

The easier way would be to use prefetch_related to preload all the objects, and then just iterate:

followups = []
for story in user.story_set.all().prefetch_related():
    followups.extend(story.followup_set.all())

Alternatively, you could do:

followups = Followup.objects.filter(story__in = user.story_set.all())

(The second piece of code might need a list compression to use IDs and not objects, but you get the idea)

Upvotes: 1

Related Questions