Reputation: 59
I've got a model that includes:
class Campaign(models.Model):
campaign_name = models.CharField(max_length=120)
.
.
.
class Character(models.Model):
name = models.TextField(max_length=50)
.
.
.
def __unicode__(self):
return u'%s' % (self.name)
class Rank(models.Model):
campaign_id = models.ForeignKey('Campaign')
character_id = models.ManyToManyField(Character)
rank = models.IntegerField(blank=True)
.
.
.
In my template that shows all the details of the campaign I also want to include the characters and their rank for that specific campaign, I've tried the GenericRelation route and reverse traversal with no luck. I'm on django 1.5.1
Upvotes: 0
Views: 324
Reputation: 19983
From this it looks like characters aren't related to a campaign directly, but only through their rank. Correct?
In that case, given campaign campaign
, then all of the ranks associated with the campaign are campaign.rank_set
(you can change the name by specifying related_name
on the rank's ForeignKey to campaign).
For each of the ranks you fetch like that, assuming you loop over the set and call individual ranks rank
, you can find the set of characters with rank.character_id
and loop over them just like you do with ranks.
If you have the character object and want to find all of the ranks associated with it, then you can do character.rank_set
.
You should probably rethink your nomenclature, but I can't advise you on how to do that without knowing more about what a rank
is for exactly and why it's related to the other models as it is.
Also, keep in mind that as it is right now, a character can have multiple ranks. If you want characters to only have one rank, then you need to remove the ManyToMany field from rank and instead put a ForeignKey field to rank on character.
{% for rank in campaign.rank_set %}
<p>Characters for {{ rank }}:</p>
<ul>
{% for character in rank.character_id %}
<li>{{ character }}</li>
{% endfor %}
</ul>
{% endfor %}
Upvotes: 3