hi
i'm new with python and django and i work on search page of my site.
in my html search form, user can choose table(or field) which want to search. in server-side i use sequences of 'if' to find chosen table(or field) and related django model.

...
#here assumed searched fields have the same name('title')
q = requst.GET['query']
tbl = requst.GET['table']
if tbl == 'Book':
    result = Book.objects.filter(title__icontains=q)
if tbl == 'Author':
    result = Author.objects.filter(title__icontains=q)
...

now is there any way to reduce or eliminate 'if' sequences?
i test this and it works:

...
tbl = eval(requst.GET['table'])
...

but i'm not sure that is best way?
thanks

You could try

tbl_name = requst.GET['table']
try:
    tbl = vars()[tbl_name]
except KeyError:
    raise # handle unknown variable case differently if you want
tbl.objects.filter(title__icontains=q)

It's much safer than eval because eval can run any code, so should be avoided with data coming from the web.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.