QuerySets in Dictionaries
Diez B. Roggisch
deets at nospam.web.de
Sat Nov 14 03:32:53 EST 2009
scoopseven schrieb:
> On Nov 12, 8:55 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> On Thu, 12 Nov 2009 10:39:33 -0800, scoopseven wrote:
>>> I need to create a dictionary of querysets. I have code that looks
>>> like:
>>> query1 = Myobject.objects.filter(status=1)
>>> query2 = Myobject.objects.filter(status=2)
>>> query3 = Myobject.objects.filter(status=3)
>>> d={}
>>> d['a'] = query1
>>> d['b'] = query2
>>> d['c'] = query3
>>> Is there a way to do this that I'm missing?
>> I don't understand your problem. Assuming Myobject is defined, and has
>> the appropriate attribute objects.filter, the above should work exactly
>> as you give it.
>>
>> What is your actual problem? Are you asking for help in defining a
>> queryset?
>>
>> --
>> Steven
>
> 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.
Why do you need this to use exec? And it seems that executable_string is
superflous - or do you want the side-effect? But then, you have the
results in d already.
query = Thing.objects.filter(type="%i" % thing.id).order_by('-date')[:3]
d[query_name] = query
As a rule of thumb: if you think you need exec, you don't.
Diez
More information about the Python-list
mailing list