Joseph Smith
Joseph Smith

Reputation: 29

Select and filter related models

I have the following models:

class Competition(models.Model):
    # ...

class Result(models.Model):
    # ...
    competition = ForeignKey(Competition, on_delete=models.CASCADE,
                             related_name='individual_results',
                             related_query_name='individual_results')
    athlete = ForeignKey(Athlete, on_delete=models.CASCADE)

class Athlete(models.Model):
    # ...

What I'd like to do is create an overview for each athlete and display the results for that athlete grouped by competition.

Tried something like this:

athlete = Athlete.objects.get(pk=1)
competitions = Competition.objects
                .prefetch_related('individual_results')
                .filter(individual_results__athlete=athlete)

But when I do competition.indvidual_results.all in a template, it displays all results from the competition and not only the ones for that athlete.

Upvotes: 1

Views: 26

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476554

A .filter(..) does not filter the related managers. It can be used to filter when you aggregate, but not items in the prefetch manager.

You can however use a Prefetch object [Django-doc], like:

results = Result.objects.filter(athlete_id=1)
competitions = Competition.objects.prefetch_related(
    Prefetch('individual_results', queryset=results, to_attr='athlete_results')
)

Now the individual results for the athlete with id=1, are stored in an attribute athlete_results in the Competitions that arise from this queryset.

Upvotes: 1

Related Questions