如何从Django模板中的相关对象获取值
我对python和django颇为新颖,如果话题已被覆盖,我很抱歉,但我没有找到我的问题的答案。如何从Django模板中的相关对象获取值
我在我的models.py
class Category(models.Model):
category_type = models.CharField(max_length=50)
description = models.TextField()
def __unicode__(self):
return self.category_type
class Area(models.Model):
area_type = models.CharField(max_length=50)
description = models.TextField()
def __unicode__(self):
return self.area_type
class Topic(models.Model):
topic_type = models.CharField(max_length=50)
description = models.TextField()
def __unicode__(self):
return self.topic_type
class Tag(models.Model):
tag_type = models.CharField(max_length=50)
description = models.TextField()
def __unicode__(self):
return self.tag_type
class GenericRecord(models.Model):
document_title = models.CharField(max_length=500)
category = models.ForeignKey("Category")
area = models.ForeignKey("Area")
topic = models.ForeignKey("Topic")
tag = models.ForeignKey("Tag")
note = models.TextField(null=True, blank=True)
link = models.TextField(null=True, blank=True)
file_upload = models.FileField(upload_to='GenericRecord/', null=True, blank=True)
class Meta:
abstract = True
class Document(GenericRecord):
code = models.CharField(max_length=500, null=True, blank=True)
reference = models.CharField(max_length=500)
issue_date = models.DateField(auto_now=False, auto_now_add=False)
validation_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
def get_admin_url(self):
return reverse("admin:%s_%s_change" % (self._meta.app_label, self._meta.model_name), args=(self.id,))
def __unicode__(self):
if self.code:
return "%s-%s" % (self.code, self.document_title)
else:
return "--%s" % self.document_title
theese类和这段代码在views.py
def documents_list(request):
# Generate counts of some of the main objects
num_docs=Document.objects.all().count()
docs=Document.objects.all()
num_articles=Article.objects.all().count()
articles=Article.objects.all()
template='documents_management.html'
for object in docs:
object.fields = dict((field.name, field.value_to_string(object)) for field in object._meta.fields)
# Render the HTML template documents_management.html with the data in the context variable
return render(request,template, context={'docs':docs, 'num_docs':num_docs,'docs':docs, 'num_articles':num_articles, 'articles':articles})
在模板中,我试图让一个表的所有值,但是对于相关对象,我得到主键(当然)。
这里是我的模板代码:
<table class="w3-table-all">
{% for object in docs %}
{%if forloop.first %}
<tr>
{% for field, value in object.fields.iteritems %}
<th>{{ field }}</th>
{% endfor %}
</tr>
{%endif%}
{% endfor %}
{% for object in docs %}
{% for field, value in object.fields.iteritems %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
我的问题是,我怎么能得到的对象类别,地区等...为了得到category_type,area_type等价值?
谢谢!
下面是从文档一个很好的例子:https://docs.djangoproject.com/en/1.11/intro/tutorial03/#use-the-template-system
你所寻找的是question.choice_set.all
一部分。
UPDATE由于不良作风
正如丹尼尔提到的一个提示你应该沟Field.to_value_string
方法。
因为我不是隐代码球迷,我总是建议代码模板显式地,在这里会被我的版本的模板
<table class="w3-table-all">
{% for doc in docs %}
{% if forloop.first %}
<tr>
<th>Document Title</th>
<th>Category Type</th>
<th>Area Type</th>
<th>...</th>
</tr>
{% else %}
<tr>
<td>{{ doc.document_title }}</td>
<td>{{ doc.category.category_type }}</td>
<td>{{ doc.area.area_type }}</td>
<td>...</td>
</tr>
{% endif %}
{% endfor %}
</table>
的我改变什么:
-
只
- 一个for循环,你开始与
if forloop.first
你可能也完成了其他情况下 - 重构
object
到doc
,因为对象经常在django模式内使用升经理 - 字段添加明确
doc.area.area_type
,这将防止一个新的领域模型也出现在模板,但在这里我建议明确了隐式的编码风格
您也可以从document_list
删除此:
for object in docs:
object.fields = dict((field.name, field.value_to_string(object)) for field in object._meta.fields)
问题在于你在使用Field.value_to_string
。正如该方法的文档字符串所示,这是为了序列化,而不是用于显示值。
这样做更简单更有效的方法是使用getattr
,它获得实际值;然后模板将把这些转换为一个字符串,在外键的情况下将调用相关对象的方法__unicode__
。
object.fields = dict((field.name, getattr(obj, field.name)) for field in object._meta.fields)
感谢您的澄清。现在我正在寻找一种方法来订购价值...... – MasVincy
这是用于反向关系。 OP希望展现关系。 –
尽管这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/17523854) – horcrux
嗨,thx的反馈你是绝对正确的。我更新了我的答案,希望能够弥补它^^ –