Thursday, March 1, 2012

Re: Seeking sample template code for iterating nested QuerySet

On Fri, Mar 2, 2012 at 08:04, brycenesbitt <digitalbitstream@gmail.com> wrote:
> The documentation at:
> https://docs.djangoproject.com/en/1.3/topics/db/queries/
>
> Speaks of "Spanning multi-valued relationships", with an QuerySet
> returning all Entries (and their Blogs) where the Blog matches a
> pattern.
>
> What does the view code look like?
>
>
>
> When I do something similar:
>
> facets= models.Category.objects.
>    filter(facetquestion__facetanswer__subject='test').
>    select_related()
> {% for category in answers %}
>        {% for q in category.facetquestion_set.all %}
>            {% for a in q.facetanswer_set.all %}
>            {% endfor %}
>        {% endfor %}
> {% endfor %}
>
> Each '_set.all" returns the entire set, not just those entries that
> matched a pattern.
>
>
>
> Back to the django documentation: how would I write the view for the
> example given:
> Blog.objects.filter(entry__headline__contains='Lennon',entry__pub_date__year=2008)
> Where I want the view to print:
>
>   Blog1
>    Entry1 "Lennon On Ice"
>    Entry2 "Lennon In Love"
>  Blog4
>    Entry9 "Lennon is Killed"
>

You are mainly listing entries here, not blogs. Because of that it's
easier to write the code like this:

blogs = SortedDict()
for entry in Entry.objects.filter(headline__contains='Lennon',
...).select_related('blog'):
blogs.setdefault(entry.blog, []).append(entry)


Your example might be better written in a similar way too:


categories = SortedDict()
for answer in FacetAnswer.objects.filter(subject__icontains='test').select_related('question__category'):
category = categories.setdefault(answer.question.category, SortedDict())
category.setdefault(answer.question, []).append(answer)

I hope something like this gets you started.

Btw, the BIG advantage of the approach outlined above is that you only
need one SQL query to fetch all results you need instead of dozens.


Matthias

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment