0

I'm building my filters as a list but having trouble building them with the Q function. It seems to be that doing things manually the filters work but when trying to build up the filters by concatenating strings I get the following issues:

Here is the Query:

MyLocationFilter = BuildQueryORFilter('MyLocationCountryCode', MyLocationCodePref1)
list = AboutMe.objects.order_by('MyLinkedInLastName').filter(reduce(OR, MyLocationFilter))

And here is how I am building those Filters:

def BuildQueryORFilter(fieldname, fieldvalues):
    QueryList = []
    spltfieldvalues = fieldvalues.split()
    for item in spltfieldvalues:
        strpitem = item.strip('[],')
        queryitem = Q(fieldname+"__contains="+strpitem)
        QueryList.append(queryitem)
    return QueryList

However the problem seems to be how to get Q(..) in the form of Q(fieldname__contains=gb) rather than Q('fieldname__contains=gb') which seems to be throwing up issues such as:

ValueError
Exception Value:    
need more than 1 value to unpack

How should I build the Q queries to avoid this unpacking issue?

Traceback for possible answer (below)

Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/brett/LinkedIn/phaseone/jelt/views.py" in AboutMeList
  259.  list = AboutMe.objects.order_by('MyLinkedInLastName').filter(MyLocationFilter)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in filter
  624.         return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in _filter_or_exclude
  642.             clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_q
  1250.                             can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_filter
  1056.         arg, value = filter_expr

Exception Type: ValueError at /list/
Exception Value: need more than 1 value to unpack
4

1 回答 1

2

通过解压字典来传递关键字参数。

    strpitem = item.strip('[],')
    key = fieldname + "__contains"
    d = {key: strpitem}
    queryitem = Q(**d)
于 2013-09-21T15:36:43.647 回答