[Fixed]-Connecting Two Models and Only Displaying in Template When they have a relationship

1👍

PxS is the through table in a many-to-many relationship. You should define that relationship explicitly:

class Season(models.Model):
    ...
    players = models.ManyToManyField('Player', through='PxS')

Now, in your season view, rather than sending all players explicitly to the template, you can just send the season; then when you iterate through seasons you can just use s.players.all to get the players for that season.

(Note, you shouldn’t set primary keys explicitly unless you have a very good reason. Django automatically allocates an id field as the pk, so your PxS model does have one; the only thing you’ve done by defining the sid and pid pks explicitly is a) renaming them and b) disabling the autoincrement, which you certainly shouldn’t do.)

Leave a comment