django如何向后追踪关系? [英] django how to following relationships backwards?
本文介绍了django如何向后追踪关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些问题,以下关系向后。从父母页面我想能看到孩子属于那个父母。感谢我到目前为止
I am having some issue with following relationships backwards. From the parent page i want to be able to see what children belong to that parent. Heres what i got so far
model.py
class Parents(models.Model):
name = models.CharField()
class Child(models.Model):
parent = models.ForeignKey(Parent, related_name='children')
child_name = models.CharField()
views.py
def parents(request):
return render_to_response('dashboard/parent.html', {'parents': Parents.objects.all() })
parent.html
parent.html
{% for parent in parents %}
<tr>
<td><a href="/parent/get/{{ parent.id }}/">{{ parent.id }}</a></td>
<td><a href="/parent/get/{{ parent.id }}/">{{ parant.name }}</a></td>
<td><a href="/parent/get/{{ parent.id }}/">{{ parent.children.child_name }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
推荐答案
Roseman提到你可能每个父母有一个以上的孩子,所以你必须得到整个孩子,并重复一遍。
As Daniel Roseman mentioned you possibily have more than one child per parent, thus you have to get the whole set of children and iterate over it.
你可以得到这个设置: code> parent.children_set.all()
You can get this set with: parent.children_set.all()
这篇关于django如何向后追踪关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文