1 Reply Latest reply: Sep 14, 2011 7:16 AM by 537206 RSS

    XQuery Python and Django QuerySet iteration problem

    537206
      Dear gurus,

      The following code using an XQuery against a list of XML documents works fine in the Python shell and I get a list of XML documents with the relevant element where the query string resides.

      from bsddb3.db import *
      from dbxml import *

      myManager = XmlManager() #XmlManager
      myContainer = myManager.openContainer("../gutorglyn.bdbxml") #XmlContainer
      myContext = myManager.createQueryContext() #XmlQueryContext

      myQuery = r"for $lines in collection('../myContainer.bdbxml')//div[@type='lev1']/lg/l where some $line in $lines satisfies (contains($line, 'ond')) return $lines"
      results = myManager.query(myQuery, myContext) #XmlResults

      for value in results:
      document = value.asDocument()
      name = document.getName()
      content = value.asString()

      print name + " - " + content + str(results.size())

      del myContainer

      However, when I try to return the same list of results and pass them to a Django template for rendering I only ever get the first result in the list.

      return render_to_response('myapp/searchResults.html', {'searchHits': content})

      I cannot work out how to get the full list of results to show. As far as I can see it is easy to iterate a result set in Django using something like the following:

      {% for hit in searchHits%}
      {{hit}}
      {% endfor %}

      but this method expects a dictionary object and as far as I can tell the XmlValue object is an unconnected list of strings.

      I'm guessing that I need to turn the XmlResults into a dictionary object or maybe use the Django queryset API but I'm not sure where to start.

      If anyone has any suggestions I'd really appreciate a leg up.

      kind regards
        • 1. Re: XQuery Python and Django QuerySet iteration problem
          537206
          I found the answer so I thought I'd share.

          The solution I needed involved appending items to a dictionary object during a for loop:

          myDict = {}
          for value in results:
          document = value.asDocument()
          name = document.getName()
          content = value.asString()
          myDict[name] = content

          return render_to_response('gutorglyn/searchResults.html', {'searchHits': hitList'})

          in the Django template you iterate through the dictionary like this:

          {% for name,content in searchHits.items%}
          {{content}}

          {{name}}
          {% endfor %}

          hope this helps someone out in the future

          regards