QuerySets in Dictionaries

Jerry Hill malaclypse2 at gmail.com
Fri Nov 13 23:37:09 CET 2009


On Fri, Nov 13, 2009 at 5:10 PM, scoopseven <mark.kecko at gmail.com> wrote:

> I actually had a queryset that was dynamically generated, so I ended
> up having to use the eval function, like this...
>
> d = {}
> for thing in things:
>        query_name = 'thing_' + str(thing.id)
>        query_string = 'Thing.objects.filter(type=' + str(thing.id) +
> ').order_by(\'-date\')[:3]'
>        executable_string = query_name + ' = Thing.objects.filter
> (type=' + str(thing.id) + ').order_by(\'-date\')[:3]'
>        exec(executable_string)
>        d[query_name] = eval(query_string)
>
> And no, this is not based on user-generated input.
>

I don't get it.  If you're already storing the name to query mapping in a
dictionary, why do you also need to use exec to do the same thing in the
local namespace?  If you're generating these names dynamically (which you
obviously are, based on this snippet), it's going to be faster and more
legible if you just look them up in the dictionary, instead of having to use
exec and eval all over the place.

Then all you'd need is something like:

d = {}
for thing in things:
       query_name = 'thing_%d' % thing.id
       d[query_name] = Thing.objects.filter(type=thing.id
).order_by('-date')[:3]

then later you just look them up as d['thing_1'] (or d[thing_name] if you're
dynamically generating the names again).

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091113/4e640b7f/attachment.html>


More information about the Python-list mailing list