Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?

Given a situation in Django 1.0 where you have extra data on a Many-to-Many relationship:

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()

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?

I know it is possible to query directly against the intermediary table to get the extra data. For example:

TeamPlayer.objects.get(player=790, team=168).captain

Or:

for x in TeamPlayer.objects.filter(team=168):
  if x.captain:
    print "%s (Captain)" % (x.player.name)
  else:
    print x.player.name

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.

like image 663
iammichael Avatar asked Jan 29 '09 20:01

iammichael


1 Answers

So, 15 minutes after asking the question, and I found my own answer.

Using dir(Team), I can see another generated attribute named teamplayer_set (it also exists on Player).

t = Team.objects.get(pk=168)
for x in t.teamplayer_set.all():
  if x.captain:
    print "%s (Captain)" % (x.player.name)
  else:
    print x.player.name

Not sure how I would customize that generated related_name, but at least I know I can get to the data from the template without adding additional query results into the context.

like image 164
iammichael Avatar answered Nov 15 '22 13:11

iammichael