1

I want to write code in a singe line to replace the following if-else code. Can I somehow use the status variable in the filter function directly as an attribute ?

status = request_queries.get('status', None)
if status == 'saved':
    queryset = queryset.filter(saved = True)
elif status == 'shortlisted':
    queryset = queryset.filter(shortlisted = True)
elif status == 'accepted':
    queryset = queryset.filter(accepted = True) 
elif status == 'rejected':
    queryset = queryset.filter(rejected = True)

2 Answers 2

1

If you can assume status will have as name a valid column name (that is a boolean field), you can use dictionary unpacking here:

status = request_queries.get('status', None)
queryset = queryset.filter(**{ status: True })

You might however want to check if it passes a valid column name, like:

status = request_queries.get('status', None)
if status in {'saved', 'shortlisted', 'accepted', 'rejected'}:
    queryset = queryset.filter(**{ status: True })
Sign up to request clarification or add additional context in comments.

2 Comments

Getting the following error: "filter() keywords must be strings"
@user11879807: that's because if status is missing in the request_queries.get('status', None), it will return None, and hence error. This is one of the reasons why you should guard this with a membership check.
1

You can build a dict with the arguments and use it with **:

status = request_queries.get('status', None)
kwargs = {status: True}
queryset = queryset.filter(**kwargs)

Comments

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.