开发者

django model filter question

I have a model which I need to filter based on different conditions. I want to avoid having to write complicated nested conditions and fitting a model filter onto every situation.

Is there anyway to concatenate or combine the filter() arguments into a variable and then put that variable as a set o开发者_Go百科f filter arguments like this?:

db_table.objects.filter(variable_of_arguments)

being equal to:

db_table.objects.filter(
    (Q(first_name__icontains=search) | 
     Q(last_name__icontains=search)), 
     foo = True)


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜