I am trying to filter some IDs using a django query and trying to do it efficiently, I want to get the same result I got from a less efficient function I created before, but I am getting an issue with the dictionary key using Q
from tmd import models
from django.db.models import Q
category = {
"utility": models.Account.UTILITY,
"system": models.Account.SYSTEM
}
country = {
"United States": models.Country.objects.get(name='USA'),
"Canada": models.Country.objects.get(name='CA'),
}
def get_a(stage=None, **kwargs):
base_args =[]
base_args.append(Q(stage__in=stage))
for key, value in kwargs.items():
base_args.append(Q(key= value))
a_ids = models.Account.objects.filter(*base_args).values_list('id', flat=True)
print("Number of a_ids: {}".format(a_ids.count()))
return a_ids
input:
a_ids = get_a(country=country["USA"], category=category["utility"])
The issue is located exactly in this line:
base_args.append(Q(key= value))
If I can make an input that changes the key for every iteration, this will be solved
CodePudding user response:
You want
base_args.append( Q( **{ key: value} ))
I'm wondering whether you need Q. The same way of handling dynamic kwargs can get you to
a_ids = models.Account.objects.filter( stage__in=stage
) .filter( **kwargs
)
which is and-logic of the various keyword=value filter terms