views:

242

answers:

3

I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax.

The use case is a form defined like this:

class SearchForm(forms.Form):
    text = forms.CharField()
    metadata = forms.CharField()
    figures = forms.CharField()

Upon submission, the form needs to generate a url-encoded string to pass to a URL client that looks like this:

text:myKeyword1+AND+metadata:myKeyword2+AND+figures:myKeyword3

Seems like there should be a simple way to do this. The closest I can get is

for f, v in request.POST.iteritems():
   if v:
       qstring += u'%s\u003A%s+and+' % (f,v)

However in that case the colon (\u003A) generates a Solr error because it is not getting encoded properly.

What is the clean way to do this?

Thanks!

A: 

Isn't u'\u003A' simply the same as u':', which is escaped in URLs as %3A ?

qstring = '+AND+'.join(
    [ u'%s%%3A%s'%(f,v) for f,v in request.POST.iteritems() if f]
    ) 
Joe Koberg
andyashton
Whoops. Should have read more closely.
Joe Koberg
+1  A: 

I would recommend creating a function in the form to handle this rather than in the view. So after you call form.isValid() to ensure the data is acceptable. You can invoke a form.generateSolrQuery() (or whatever name you would like).

class SearchForm(forms.Form):
  text = forms.CharField()
  metadata = forms.CharField()
  figures = forms.CharField()

  def generateSolrQuery(self):
    return "+and+".join(["%s\u003A%s" % (f,v) for f,v in self.cleaned_data.items()])
mountainswhim
Great solution, thanks! Just to note, I think that newer versions of python use "cleaned_data" instead of "clean_data". Not sure if that is accurate though.
andyashton
your right, that was a typo. I fixed my original answer
mountainswhim
A: 

Use django-haystack. It takes care of all the interfacing with Solr - both indexing and querying.

Daniel Roseman
Thanks! I'll check it out. I'm already using Solrpy, which seems nice and lightweight for my purpose.
andyashton