Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: template access value from many to many through table

Tags:

django

I have the following table models.

class Experience(models.Model):
    name = models.CharField(max_length=50)

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    about = models.TextField()

    def __unicode__(self):
        return self.name

class Level(models.Model):
    level = models.IntegerField()
    details = models.TextField()

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    started = models.IntegerField(default=0)
    completed = models.IntegerField(default=0)

    exp = models.ManyToManyField(Experience, through='ExperienceLinks')

    def __unicode__(self):
        return "Level %i" % self.level



class ExperienceLinks(models.Model):
    experience = models.ForeignKey(Experience, on_delete=models.CASCADE)
    level = models.ForeignKey(Level, on_delete=models.CASCADE)

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    modifier = models.IntegerField(default=1)

Passing in a level object to the template I'm trying to get the modifier for the experience for the level. I'm trying

  {% for exp in level.exp.all %}

      <p><span class="label label-secondary ">{{ exp }} (+{{ exp.modifier }})</span></p>

  {% endfor %}

I'm only getting the following for an output

exp1 (+)
exp2 (+)

So I can't access the modifier how i'd like to.

Thanks for the help

like image 921
Mike Avatar asked Jul 13 '16 18:07

Mike


1 Answers

I think you want to call the through object in your template rather than the object that was passed into the M2M field.

  {% for exp in level.experiencelinks_set.all %}

  <p><span class="label label-secondary ">{{ exp }} (+{{ exp.modifier }})</span></p>

  {% endfor %}

Use level.experiencelinks_set.all not level.exp.all.

like image 134
marcusshep Avatar answered Oct 07 '22 13:10

marcusshep