Query when parameter is none django

前端 未结 5 1326
春和景丽
春和景丽 2020-12-31 09:50

I want to make a query, something like

Model.objects.filter(x=x).filter(y=y).filter(z=z) 

... but there are some cases when for example y

5条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 10:10

    I do not know, if I get your question, but

    Model.objects.filter(x=x, y__isnull = False, z=z)
    

    gives you the queryset, where the ycolumn is non-null (IS NOT NULL).

    Here's the relevant documentation.

    EDIT: Check if y is None and build your queryset dynamically:

    if y is None:
        qs = Model.objects.filter(x=x).filter(z=z)
    elif z is None:
        qs = Model.objects.filter(x=x).filter(y=y)
    ...
    

    If there are too many arguments to deal with, you could use something like this; assuming that x, y, z are stored in a dictionary your values:

    your_values = { 'x' : 'x value', 'y' : 'y value', 'z' : 'value'}
    arguments = {}
    for k, v in your_values.items():
        if v:
            arguments[k] = v
    
    Model.objects.filter(**arguments)
    

提交回复
热议问题