[英]django foreign key table fields in html template
I have two tables(article,comment) are related one to many relashionship using a foreign key.我有两个表(文章、评论)使用外键关联一对多关系。 I would have want in the html template list and some fields from the table one article but that I create don't work,here the code:
我想要 html 模板列表和表中的一些字段,但我创建的文章不起作用,这里是代码:
models.py模型.py
class article(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
last_name = models.CharField(max_length=254)
age = models.CharField(max_length=254)
def __unicode__(self):
return str(self.id)
class comment(models.Model):
field_1 = models.CharField(max_length=100, blank=True, null=True)
field_2 = models.CharField(max_length=254)
field_3 = models.CharField(max_length=254)
field_fk= models.ForeignKey('article', blank=True, null=True)
def __unicode__(self):
return str(self.id)
views.py视图.py
def index(request):
apps = article.objects.all()
comments = comment.objects.all()
return render(request, 'index.html', {'apps':apps,'comments':comments})
html template: html 模板:
{% for b in apps %}
<p>{{ b.field_1 }}</p>
<p>{{ b.field_2 }}</p>
<p>{{ b.field_3 }}</p>
{% for c in b.field_fk.comments %}
<p>{{ c.name }},{{ c.last_name}},{{ c.age}}</p>
{% endfor %}
{% endfor %}
in my example in the template don't show me name
, last_name
and age
is empty the paragraph在我的模板示例中,不显示
name
、 last_name
和age
为空段落
You can't access the comments using just .comments
. 您不能仅使用
.comments
访问评论。 Use modelname_set. 使用modelname_set。 In your case it would be
comments_set
. 在您的情况下,将为
comments_set
。 Your for-loop will look like this: 您的for循环将如下所示:
{% for c in b.field_fk.comment_set.all %}
<p>{{ c.name }},{{ c.last_name}},{{ c.age}}</p>
{% endfor %}
Also, you aren't looping the correct model. 另外,您没有循环使用正确的模型。
apps
is set to Article but in your template you are using the Comment fields (field_1, field_2...). apps
设置为Article,但是在您的模板中,您使用的是Comment字段(field_1,field_2 ...)。 The first part should be: 第一部分应该是:
{% for article in apps %}
<p>{{ article.name}}</p>
<p>{{ article.last_name}}</p>
<p>{{ article.age}}</p>
...
Since the article is the main loop you don't to use the foreign key. 由于文章是主循环,因此您无需使用外键。 The loop should use the comment_set directly:
循环应直接使用comment_set:
{% for comment in b.comment_set.all %}
<p>{{ comment.field_1 }},{{ comment.field_2 }},{{ comment.field_3}}</p>
{% endfor %}
use this code使用此代码
views.py:意见.py:
def index(request):
comments = comment.objects.all()
return render(request, 'index.html', {'comments':comments})
HTML template: HTML模板:
{% for b in comments %}
<p>{{ b.field_1 }}</p>
<p>{{ b.field_2 }}</p>
<p>{{ b.field_3 }}</p>
<p>{{ b.field_fk.name }},{{ b.field_fk.last_name}},{{ b.field_fk.age}}</p>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.