Dynamic query based on querystring parameters

77 views
Skip to first unread message

Masud

unread,
Feb 27, 2013, 4:24:00 AM2/27/13
to python-...@googlegroups.com
Hi all,

I am new to sunburnt and am looking to incorporate it in Django.

I have a question at this moment. 

Why can I not use a variable to define the field in which I want to query, e.g. at the moment, I have to check query string and then assign the actual solr schema field as shown below inside the query().

        query = request.GET['q']
        field = request.GET['field']
        if field == 'all':
            field_query = solr.query(text=query)
        elif field == 'title':
            field_query = solr.query(title=query)
        elif field == 'author':
            field_query = solr.query(author=query)
        elif field == 'company':
            field_query = solr.query(company=query)
        elif field == 'keywords':
            field_query = solr.query(keywords=query)
        elif field == 'year':
            field_query = solr.query(year=query)

whereas, this would be so much simpler.

        query = request.GET['q']
        field = request.GET['field']
        if field == 'all':
            field_query = solr.query(text=query)
        else:
            field_query = solr.query(field=query)    #note field here which is not defined in solr schema but is a python variable

Thanks for your help in advance.

Best wishes,
Masud

Andrew Montalenti

unread,
Feb 27, 2013, 7:28:28 AM2/27/13
to python-...@googlegroups.com

Masud,

This will work:

query_args = {field: query}
solr.query(**query_args)

This is just a built-in Python feature, "keyword argument application from a dictionary".

-Andrew

--
You received this message because you are subscribed to the Google Groups "Python Sunburnt" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-sunbur...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Masud

unread,
Feb 27, 2013, 11:53:44 AM2/27/13
to python-...@googlegroups.com
Fantastic, thanks a lot. I can't believe I missed this.

Best wishes,
Masud
Reply all
Reply to author
Forward
0 new messages