我遇到类似的情况:
# models
class Entity(models.Model):
name = models.TextField()
class Member(models.Model):
entity = models.ForeignKey('common.Entity', help_text="FKey relationship to Entity table")
name = models.TextField()
# view
def details(request, eid):
entity = Entity.objects.select_related().get(id=eid)
entity.entity_test = 'oh yeah'
for member in entity.member_set.all():
member.member_test = 'oh noes'
response = {
'entity': entity,
}
return render_to_response(
'common/details.html',
{'response': response},
context_instance=RequestContext(request)
)
# html template
visible -> {{ response.entity.entity_test }}<br />
{% for member in response.entity.member_set.all %}
not visible -> {{ member.member_test }} <!-- WHY? -->
{% endfor %}
那么,我如何在每个member
设置一个属性,以便我可以在模板中使用它?
答案 0 :(得分:2)
您没有在循环中修改member_set
。将entity.member_set.all()
的结果存储在列表变量中,然后在循环中修改它的项目:
entity_members = entity.member_set.all()
for member in entity_members:
member.member_test = 'oh noes'
response = {
'entity': entity,
'entity_members': entity_members
}
然后,在模板中:
{% for member in entity_members %}
{{ member.member_test }}
{% endfor %}
希望有所帮助。