Search code examples
djangofor-loopneomodel

Nested for-cycles in Django templates


I am using Django my a NoSQL graph database, and the Neomodel binding to link them. Querying it in my local shell, I have everything correct:

city = PlaceName.index.search(name='Sargans')

for x in city:
    results = x.traverse('hasid')
    for  y in results:
        print x.name, x.type, y.loc_id
   ...:         
Sargans orig loc000928
Sargans std loc000010
Sargans orig loc000010
Sargans orig loc000654
Sargans std loc000925
Sargans orig loc000063
Sargans orig loc000011
Sargans orig loc000929

I want to get the same output through my Django-app, but what I get is:

Sargans orig loc000929
Sargans std loc000929
Sargans orig loc000929
Sargans orig loc000929
Sargans std loc000929
Sargans orig loc000929
Sargans orig loc000929
Sargans orig loc000929 

As if the second loop goes over the same entity every time...

PlaceName class:

class PlaceName(StructuredNode):
    name = StringProperty(index=True, required=True)
    lang = StringProperty(index=True, required=True)
    type = StringProperty(index=True, required=True)#std/orig
    hasid = RelationshipTo('PlaceId', 'HAS_ID')
    descr = RelationshipTo('Desc', 'HAS_DESC')

In my views.py:

placenames = PlaceName.index.search(name=q)
for x in placenames:
    results = x.traverse('hasid')

return render_to_response('search_results.html',
                                      {'placenames':placenames, 'query':q, 'res':results})

In my templates:

{% for x in placenames %}
   {% for y in res %}

 <a>   {{ x.name }} {{ x.type  }} {{ y.loc_id }} </a><br></li>

    % endfor %}
 {% endfor %}

How to write the correct template ?


Solution

  • You need the full list of results for each placename.

    In views.py:

    places = [{'placename': x, 'results': x.traverse('hasid')} for x in placenames]
    return render_to_response('search_results.html', {'places': places})
    

    In the template:

    {% for x in places %}
        {% for y in x.results %}
            <a>   {{ x.placename.name }} {{ x.placename.type  }} {{ y.loc_id }} </a><br></li>
        {% endfor %}
    {% endfor %}