Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6208195
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T05:46:02+00:00 2026-05-24T05:46:02+00:00

I’m having an odd problem using itertools.groupby to group the elements of a queryset.

  • 0

I’m having an odd problem using itertools.groupby to group the elements of a queryset. I have a model Resource:

from django.db import models 

TYPE_CHOICES = ( 
    ('event', 'Event Room'),
    ('meet', 'Meeting Room'),
    # etc 
)   

class Resource(models.Model):
    name = models.CharField(max_length=30)
    type = models.CharField(max_length=5, choices=TYPE_CHOICES)
    # other stuff

I have a couple of resources in my sqlite database:

>>> from myapp.models import Resource
>>> r = Resource.objects.all()
>>> len(r)
3
>>> r[0].type
u'event'
>>> r[1].type
u'meet'
>>> r[2].type
u'meet'

So if I group by type, I naturally get two tuples:

>>> from itertools import groupby
>>> g = groupby(r, lambda resource: resource.type)
>>> for type, resources in g:
...   print type
...   for resource in resources:
...     print '\t%s' % resource
event
    resourcex
meet
    resourcey
    resourcez

Now I have the same logic in my view:

class DayView(DayArchiveView):
    def get_context_data(self, *args, **kwargs):
        context = super(DayView, self).get_context_data(*args, **kwargs)
        types = dict(TYPE_CHOICES)
        context['resource_list'] = groupby(Resource.objects.all(), lambda r: types[r.type])
        return context

But when I iterate over this in my template, some resources are missing:

<select multiple="multiple" name="resources">
{% for type, resources in resource_list %}
    <option disabled="disabled">{{ type }}</option>
    {% for resource in resources %}
        <option value="{{ resource.id }}">{{ resource.name }}</option>
    {% endfor %}
{% endfor %}
</select>

This renders as:

select multiple

I’m thinking somehow the subiterators are being iterated over already, but I’m not sure how this could happen.

(Using python 2.7.1, Django 1.3).

(EDIT: If anyone reads this, I’d recommend using the built-in regroup template tag instead of using groupby.)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T05:46:03+00:00Added an answer on May 24, 2026 at 5:46 am

    I think that you’re right. I don’t understand why, but it looks to me like your groupby iterator is being pre-iterated. It’s easier to explain with code:

    >>> even_odd_key = lambda x: x % 2
    >>> evens_odds = sorted(range(10), key=even_odd_key)
    >>> evens_odds_grouped = itertools.groupby(evens_odds, key=even_odd_key)
    >>> [(k, list(g)) for k, g in evens_odds_grouped]
    [(0, [0, 2, 4, 6, 8]), (1, [1, 3, 5, 7, 9])]
    

    So far, so good. But what happens when we try to store the contents of the iterator in a list?

    >>> evens_odds_grouped = itertools.groupby(evens_odds, key=even_odd_key)
    >>> groups = [(k, g) for k, g in evens_odds_grouped]
    >>> groups
    [(0, <itertools._grouper object at 0x1004d7110>), (1, <itertools._grouper object at 0x1004ccbd0>)]
    

    Surely we’ve just cached the results, and the iterators are still good. Right? Wrong.

    >>> [(k, list(g)) for k, g in groups]
    [(0, []), (1, [9])]
    

    In the process of acquiring the keys, the groups are also iterated over. So we’ve really just cached the keys and thrown the groups away, save the very last item.

    I don’t know how django handles iterators, but based on this, my hunch is that it caches them as lists internally. You could at least partially confirm this intuition by doing the above, but with more resources. If the only resource displayed is the last one, then you are almost certainly having the above problem somewhere.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am currently running into a problem where an element is coming back from
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
I have thousands of HTML files to process using Groovy/Java and I need to
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a bunch of posts stored in text files formatted in yaml/textile (from
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.