0

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

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Gribouillis
0

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.

Edited by Gribouillis: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.