user11879807
user11879807

Reputation: 301

Replacing function attribute with variable containing string

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)

Upvotes: 1

Views: 435

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

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)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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 })

Upvotes: 1

Related Questions