Query when parameter is none django

前端 未结 5 1347
春和景丽
春和景丽 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

    A better approach on the otherwise very readable @rolling-stone answer:

    models = Model.objects.all()
    
    variables = {'x':x,'y':y,'z':z}
    
    for key, value in variables.items():
        if value is not None:
            models = models.filter(**{key: value})
    

    Anyway, depending on the specific filter, you'll need to apply filters together in the same .filter() call, so the "blind" way only works in the simple cases. See https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships for more information on those cases.

提交回复
热议问题