1

Many times I find myself writing code similar to:

query = MyModel.objects.all()
if request.GET.get('filter_by_field1'):
    query = query.filter(field1 = True)
if request.GET.get('filter_by_field2'):
    query = query.filter(field2 = False)
field3_filter = request.GET.get('field3'):
if field3_filter is not None:
    query = query.filter(field3 = field3_filter)
if field4_filter:
    query = query.filter(field4 = field4_filter)
# etc...
return query

Is there a better, more generic way of building queries such as the one above?

1 Answer 1

3

If the only things that are ever going to be in request GET are potential query arguments, you could do this:

query = MyModel.objects.filter(**request.GET)
Sign up to request clarification or add additional context in comments.

2 Comments

This makes sense. Two concerns: (1) not all arguments come from request.GET (just edited the question to reflect that) and (2) I don't want to allow filtering on every field.
Well, you can build up a dictionary with a combination of arguments from request and elsewhere, and sanitise where necessary; the theory is the same.

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.