gpt4 book ai didi

Django:模板通过表访问多对多的值

转载 作者:行者123 更新时间:2023-12-02 05:46:38 24 4
gpt4 key购买 nike

我有以下表格模型。

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

所以我无法按照我想要的方式访问修饰符。

感谢您的帮助

最佳答案

我认为您想在模板中调用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

关于Django:模板通过表访问多对多的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com