Ritambhara Chauhan
Ritambhara Chauhan

Reputation: 99

How to create dynamic variable to create NULL filter in django db query

I am running db query after getting a value from a form in Django. There are many options in the form and hence I want to pass it as variable, but also want to filter null values. Passing to values is fine as it takes a string, but I am not able to pass the variable to null filter, unless I mention it. How to pass value to null filter as a variable?

parameter = 'temperature'
TempData.objects.all().values(parameter).filter(temperature__isnull=False)

Upvotes: 1

Views: 494

Answers (2)

JPG
JPG

Reputation: 88509

If you have multiple parameters to filter out,

parameters = ['temperature', 'foo', 'bar', 'foo_bar']
null_filters = {"{}__isnull".format(param): True for param in parameters}
TempData.objects.all().values(*parameters).filter(**null_filters)

Upvotes: 2

Shakil
Shakil

Reputation: 4630

Django Orm can handle None So

parameter = 'temperature'
TempData.objects.filter(parameter=None)

should able to return what you are expecting.

Upvotes: 0

Related Questions