1

I'm doing this in my code:

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)

I was wondering if it was possible to transform this into something like:

for i in ['hobbies2', 'types_permis2', 'and so on']:
    q = q & Q(personne__i__in=i)  # obviously wrong, not working

1 Answer 1

1

Sure:

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)

Here's another approach:

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! You made my day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.