On Mon, 2009-01-26 at 07:59 -0800, Enrico wrote:
> I would like to track which items are being loaded in a queryset,
> without having to loop through the entire list.
> 
> I think the best way would be to extend the Queryset object, probably
> the "__iter__" or "iterator" methods...
> 
> But I don't want to copy-and-paste or mess with the Queryset code too
> much.

The natural Python solution here would be subclassing. Create your own
subclass of QuerySet that overrides the iterator() method (probably the
easiest one, but overriding __iter__ is an alternative). The difference
is that iterator() is called when the items are first loaded from the
database, whereas __iter__() is called every time the user iterates over
the queryset (even if it retrieves results from the queryset's cache).
Of course, iterator() is guaranteed to be called at least once, since
loading from the database is required, whereas __iter__ might never be
called.

The only potentially tricky bit to overriding iterator(), say, is to
realise that it is a Python iterator, so you won't be able to do
something like this:

        class MyQuerySet(QuerySet):
           def iterator(self):
              # Bad code! No biscuit!
              obj = super(MyQuerySet, self).iterator()
              ...
        
That's because the super() call would do a function/method call.
Instead, you'll have to do something like this (100% untested code, but
how badly could I screw it up?):

        class MyQuerySet(QuerySet):
           def iterator(self):
             for obj in super(MyQuerySet, self).iterator():
                # Do stuff with 'obj'
                yield obj
        
You have to iterator over the existing iterator and yield the result
yourself.

Then, of course, you would use a custom manager ([1]) to return your
queryset subclass instead of Django's default QuerySet for the cases you
care about.

[1]
http://docs.djangoproject.com/en/dev/topics/db/managers/#modifying-initial-manager-querysets

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to