I
I
Ilya Demyanov2015-11-20 09:24:06
Django
Ilya Demyanov, 2015-11-20 09:24:06

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)

We form the output:
def view_list_contacts(request):
    subdivisions = Subdivision.objects.all()
    contacts = Contact.objects.order_by('id')
    return render(request, URL_RENDER['view_list_contacts'], locals())

In order to display the contacts belonging to the current node in the template, I have to wool them all in a circle:
<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>

Looks crooked. Is there a less hacky solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-11-20
@turbidit

Yes. This is called feedback. If you link like this:

class A:
    b = ForeignKey(B)

That set of objects of type A that refer to b is obtained in django like this:
So in your case like this:
{% for contact in node.contact_set.all %}
    {{ contact.full_name }}
{% endfor %}

But in this case, with each iteration of {% for contact in node.contact_set.all %}, a request will be sent to the database, so you need to add to
This is how it will be optimized.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question