在我的模型中,有很多领域。我一直在努力让它们出现在模板中。一个是常规的ManyToMany字段,另一个是通过使用。问题是未显示金额。我知道目前仅在pcbuilds.components.all中为 component 定义了迭代。如何在那里管理数量?
models.py:
class Component(models.Model):
name = models.CharField(max_length=100, unique=True,help_text='Component name')
manufacturer = models.IntegerField(blank=True,null=True,choices=MANUFACTURERS)
model = models.CharField(max_length=100,unique=True,blank=True,null=True, help_text='model')
class Tag(models.Model):
title = models.CharField(max_length=100,unique=True,blank=True,null=True, help_text='tagname')
class PCBuilds(models.Model):
title = models.CharField(max_length=50, help_text='PC build title')
components = models.ManyToManyField(Component,help_text='Pick your components from the list or create and add them.',through='Componentlist')
subtitle = models.CharField(blank=True,max_length=80, help_text='Subtitle')
def __str__(self):
return self.title
class Componentlist(models.Model):
component = models.ForeignKey(Component, on_delete=models.CASCADE,related_name='components')
pcbuild = models.ForeignKey(PCBuilds, on_delete=models.CASCADE,related_name='pcbuilds')
amount = models.FloatField(null=True,help_text='amount')
模板:
<div class="card-deck">
{% for pcbuilds in object_list|slice:":3" %}
<div class="card" style="width: 18rem;">
<div class="card-header">
<a href="{% url 'pcbuilds_detail' pcbuilds.pk %}">
<span class="font-weight-bold">{{ pcbuilds.title }}</span></a> ·
<span class="text-muted">{{ pcbuilds.subtitle }}</span>
</div>
<div class="card-body">
<ul>
{% for component in pcbuilds.components.all %}
<li>{{ component.name}}{{ component.manufacturer}}{{ component.model }}{{ componentlist.amount }}</li>
{% endfor %}
</ul>
</div>
<div class="card-footer text-center text-muted">
{% for tag in recipe.tags.all %}
Tags: {{ tag.title }}
{% endfor %}
</div>
</div>
<br />
{% endfor %}
答案 0 :(得分:0)
您没有在此处定义componentlist
,因此模板将忽略它。通常,您需要遵循一种关系,就像首先要获得组件一样。但是通过这种方式就无法访问穿透表,因为您已经有效地通过了它来获取目标表。
相反,您需要遵循从pcbuild到穿透表,再从那里到组件的关系:
{% for componentlist in pcbuilds.pcbuilds.all %}
<li>{{ componentlist.component.name}}{{ componentlist.component.manufacturer}}{{ componentlist.component.model }}{{ componentlist.amount }}</li>
{% endfor %}
请注意,您在该穿透表中的相关名称很奇怪,这就是为什么我不得不使用令人困惑的pcbuilds.pcbuilds.all
。从pcbuild到componentlist的反向关系应为componentlist_set
,这是默认设置;应该没有任何理由对此进行更改。