Answer the question
In order to leave comments, you need to log in
How to output ForeignKey for MPTT tree branches?
Good afternoon.
There is a tree model of departments and their associated contacts:
class Subdivision(MPTTModel):
subdivision = models.CharField(verbose_name="subdivision", max_length=255)
parent = TreeForeignKey("self", null=True, blank=True, related_name="children")
class Contact(models.Model):
full_name = models.CharField(verbose_name="full name", max_length=255, unique=True)
subdivision = models.ForeignKey(Subdivision)
def view_list_contacts(request):
subdivisions = Subdivision.objects.all()
contacts = Contact.objects.order_by('id')
return render(request, URL_RENDER['view_list_contacts'], locals())
<ul>
{% recursetree subdivisions %}
<li>
{{ node.subdivision }}
{% for contact in contacts %}
{% if contact.subdivision.id == node.id %}
{{ contact.full_name }}
{% endif %}
{% endfor %}
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
Answer the question
In order to leave comments, you need to log in
Yes. This is called feedback. If you link like this:
class A:
b = ForeignKey(B)
{% for contact in node.contact_set.all %}
{{ contact.full_name }}
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question