我在我的代码中这样做:
programmes2 = [int(l) for l in g.getlist('programmes2')]
if len(programmes2):
q = q & Q(personne__programmes2__in=programmes2)
activites2 = [int(l) for l in g.getlist('activites2')]
if len(activites2):
q = q & Q(personne__activites2__in=activites2)
hobbies2 = [int(l) for l in g.getlist('hobbies2')]
if len(hobbies2):
q = q & Q(personne__hobbies2__in=hobbies2)
types_permis2 = [int(l) for l in g.getlist('types_permis2')]
if len(types_permis2):
q = q & Q(personne__types_permis2__in=types_permis2)
personnalites2 = [int(l) for l in g.getlist('personnalites2')]
if len(personnalites2):
q = q & Q(personne__personnalites2__in=personnalites2)
langues2 = [int(l) for l in g.getlist('langues2')]
if len(langues2):
q = q & Q(personne__langues2__in=langues2)
我想知道是否有可能将其转换为:
for i in ['hobbies2', 'types_permis2', 'and so on']:
q = q & Q(personne__i__in=i) # obviously wrong, not working
最佳答案
当然:
q = Q()
for field in ["hobbies2", "types_permis2", "and so on"]:
values = [int(l) for l in g.getlist(field)]
if values:
field_query = "personne__{}__in".format(field)
q = q & Q(field_query=values)
这是另一种方法:
fields = ["hobbies2", "types_permis2", "and so on"]
params = {"personne__{}__in".format(field): [int(l) for l in g.getlist(field)]
for field in fields
if g.getlist(field)}
result = MyModel.objects.filter(**params)
关于python - 建立查询优化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37730751/