I'm a little stuck trying to get my head around a django template.
I have 2 objects, a cluster and a node
I would like a simple page that lists...
[Cluster 1]
[associated node 1]
[associated node 2]
[associated node 3]
[Cluster 2]
[associated node 4]
[associated node 5]
[associated node 6]
I've been using Django for about 2 days so if i've missed the point, please be gentle :)
Models -
class Node(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
cluster = models.ForeignKey(Cluster)
def __unicode__(self):
return self.name
class Cluster(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
def __unicode__(self):
return self.name
Views -
def DSAList(request):
clusterlist = Cluster.objects.all()
nodelist = Node.objects.all()
t = loader.get_template('dsalist.html')
v = Context({
'CLUSTERLIST' : clusterlist,
'NODELIST' : nodelist,
})
return HttpResponse(t.render(v))
Template -
<body>
<TABLE>
{% for cluster in开发者_运维百科 CLUSTERLIST %}
<tr>
<TD>{{ cluster.name }}</TD>
{% for node in NODELIST %}
{% if node.cluster.id == cluster.id %}
<tr>
<TD>{{ node.name }}</TD>
</tr>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</TABLE>
</body>
Any ideas ?
{% for cluster in CLUSTERLIST %}
<tr>
<td>{{ cluster.name }}</td>
</tr>
{% for node in cluster.node_set.all %}
<tr>
<td>{{ node.name }}</td>
</tr>
{% endfor %}
{% endfor %}
Edit: if you want each node in it's own row below the cluster you need to edit your HTML too a bit.
Following relationships "backward"
Many-to-one relationships
It would have been helpful if you'd described what problem you were experiencing. But, you can't do this in Django 1.1:
{% if node.cluster.id == cluster.id %}
...
{% endif %}
You have to do
{% ifequal node.cluster.id cluster.id %}
...
{% endifequal %}
Of course, the right way to iterate through this sort of relationship is the way rebus has shown you.
You can just pass the clusterlist to template and then:
{% for node in cluster.node_set.all %}
<tr>
<TD>{{ node.name }}</TD>
</tr>
{% endfor %}
Your method should work as well with :
{% for node in NODELIST %}
{% ifequal node.cluster.id cluster.id %}
<tr>
<TD>{{ node.name }}</TD>
</tr>
{% endifequal %}
{% endfor %}
精彩评论