[Answered ]-Django model filter question


I’m not sure, but may be you can do it with 2 parameters:

param1 = Q(first_name__icontains=search) | Q(last_name__icontains=search))
param2 = {'foo', False}

db_table.objects.filter(param1, **param2)


You can build up a variable number of arguments and pass them in as follows:

q = Q(first_name__icontains=search) | Q(last_name__icontains=search)
p = Q(first_in_line=True) | Q(last_in_line=True)

args = [q, p]

kwargs = {
    'foo': True
    'bar': False

db_table.objects.filter(*args, **kwargs)
# Equivalent to:
# db_table.objects.filter(
#    Q(first_name__icontains=search) | Q(last_name__icontains=search),
#    Q(first_in_line=True) | Q(last_in_line=True),
#    foo=True,
#    bar=False
# )

Now you can use whatever logic you want to build up args and kwargs and the call to filter() will always be the same.


Here’s a snippet that’s been around for a while that might help: http://djangosnippets.org/snippets/1679/

👤Abid A

Leave a comment