Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
    text
    copied!<p>Given a situation in Django 1.0 where you have <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany" rel="noreferrer">extra data on a Many-to-Many relationship</a>:</p> <pre><code>class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = models.CharField(max_length=40) players = models.ManyToManyField(Player, through='TeamPlayer', related_name='teams') class TeamPlayer(models.Model): player = models.ForeignKey(Player) team = models.ForeignKey(Team) captain = models.BooleanField() </code></pre> <p>The many-to-many relationship allows you to access the related data using attributes (the "players" attribute on the Team object or using the "teams" attribute on the Player object by way of its related name). When one of the objects is placed into a context for a template (e.g. a Team placed into a Context for rendering a template that generates the Team's roster), the related objects can be accessed (i.e. the players on the teams), but how can the extra data (e.g. 'captain') be accessed along with the related objects from the object in context (e.g.the Team) without adding additional data into the context?</p> <p>I know it is possible to query directly against the intermediary table to get the extra data. For example:</p> <pre><code>TeamPlayer.objects.get(player=790, team=168).captain </code></pre> <p>Or:</p> <pre><code>for x in TeamPlayer.objects.filter(team=168): if x.captain: print "%s (Captain)" % (x.player.name) else: print x.player.name </code></pre> <p>Doing this directly on the intermediary table, however requires me to place additional data in a template's context (the result of the query on TeamPlayer) which I am trying to avoid if such a thing is possible.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload