title: Django: How do I use a string as the keyword in a Q() statement?
body: <p>I'm writing a simple search form for a certain model. Let's call the model <code>Orchard</code> and give it the attributes <code>apples</code>, <code>oranges</code>, and <code>pears</code>, just for the sake of demonstration.</p>
  
  <p>So, the form does not require all fields to be filled. So you can search on <code>apples</code> and <code>oranges</code> but not pears. I them need to filter like this:</p>
  
  <pre><code>Orchard.objects.filter(apples=request.GET.get('apples'), oranges=request.GET.get('oranges'), pears=request.GET.get('pears'))
  </code></pre>
  
  <p>but if <code>pears</code> is empty, no results will ever return.</p>
  
  <p>My first thought was to use <code>Q</code> objects, something like this:</p>
  
  <pre><code>from django.db.models import Q
  
  options = {}
  options['apples'] = request.GET.get('apples')
  options['oranges'] = request.GET.get('oranges')
  options['pears'] = request.GET.get('pears')
  
  queries = None
  
  for key in options:
      if options[key] != u'':
          if queries:
              queries &amp;= Q(key=options[key]) # &lt;=== problem here
          else:
              queries = Q(key=options[key])  # &lt;=== same problem here
  
  results = Orchard.objects.filter(queries)
  </code></pre>
  
  <p>The problem comes up in those marked lines. I obviously can't just use "key" as the attribute keyword, because it doesn't take a string, it takes essentially a variable.</p>
  
  <p>So... how do I get around this?</p>
  
  <p>Unless there's a known solution to this problem not involving <code>Q</code>. That would be helpful too.</p>