Django:通过表格从许多对许多模板的访问值 [英] Django: template access value from many to many through table

查看:50
本文介绍了Django:通过表格从许多对许多模板的访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表格模型.

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.

感谢您的帮助

推荐答案

我认为您想在模板中调用通过对象,而不是传递到M2M字段中的对象.

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 %}

使用 level.experiencelinks_set.all 而不是 level.exp.all .

这篇关于Django:通过表格从许多对许多模板的访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆