user3199840
user3199840

Reputation: 535

Querying multiple models and putting results in a table

I've got these models:

class League(models.Model):
    ...

class Game(models.Model):
    league = models.ForeignKey(League, related_name='games')
    ...

class Competitor(models.Model):
    user = models.ForeignKey(User, related_name='competitors')
    game = models.ForeignKey(Game, related_name='competitors')
    points = models.CharField(max_length=50, blank=True)
    ...

And I want to make a League-score-table in my template:

      | Game1 | Game2 | Game3 | Tot
Comp1 |       |       |   8   |  8
Comp2 |   5   |       |   1   |  6
Comp3 |       |   4   |   3   |  7

But I can't figure out how to make these kind of queries in the view. I get that I can get the Games of a League:

l = get_object_or_404(League, pk=id) 
g = l.games

And put it in the table header like this:

{% for game in g %}
<th>{{ game.name}}</th>
{% endfor %}

But how do I get the list of distinct competitors for a League of games? Even if they have only played one game in the league.

And how to I iterate the competitors over the games to get the points? What methods should I look into here? Or is it a better way to structure this?

Upvotes: 1

Views: 46

Answers (1)

Isaac Ray
Isaac Ray

Reputation: 1361

I think you should be able to do game.competitors_set.all() and get the competitors for a given game object. Maybe thats not exactly what you are looking for however. If you want to take a league object and get a query set that returns all the competitors in a league, I think what you want is:

league = League.objects.get(pk=<the league you want>)
competitors = Competitors.objects.filter(game__league=league)

~EDIT~

To do the iteration, you will want to collect the data in your view in some sort of dict in a format that makes sense for iteration, and then pass it to your template. One thing I did notice: You have "game" as a single instance for your competitor model. This implies that each competitor is only in a single game. I think you want to make that a ManyToManyField. See here for more info.

Upvotes: 1

Related Questions