我有以下表格模型。
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)
将关卡对象传递给模板我试图获得该关卡体验的修饰符。我正在尝试
{% for exp in level.exp.all %}
<p><span class="label label-secondary ">{{ exp }} (+{{ exp.modifier }})</span></p>
{% endfor %}
我只获得以下输出
exp1 (+)
exp2 (+)
所以我无法访问我想要的修饰符。
感谢您的帮助
答案 0 :(得分:4)
我认为你想在你的模板中调用through object
而不是传递给M2M字段的对象。
{% for exp in level.experiencelinks_set.all %}
<p><span class="label label-secondary ">{{ exp }} (+{{ exp.modifier }})</span></p>
{% endfor %}
使用level.experiencelinks_set.all
而非level.exp.all
。