Issue
My current code is this
class CounterFilters(TextChoices):
publications_total = "publications-total"
publications_free = "publications-free"
publications_paid = "publications-paid"
comments_total = "comments-total"
votes_total = "voted-total"
class SomeView:
def get(self, request, format=None):
user = request.user
response_data = []
if "fields" in request.query_params:
fields = request.GET.getlist("fields")
for field in fields:
if field == CounterFilters.publications_total:
response_data.append({"type": CounterFilters.publications_total, "count": some_calculations1})
if field == CounterFilters.publications_free:
response_data.append({"type": CounterFilters.publications_free, "count": some_calculations2})
if field == CounterFilters.publications_paid:
response_data.append({"type": CounterFilters.publications_paid, "count": some_calculations3})
if field == CounterFilters.comments_total:
response_data.append({"type": CounterFilters.comments_total, "count": some_calculations4})
if field == CounterFilters.votes_total:
response_data.append({"type": CounterFilters.votes_total, "count": some_calculations5})
return Response(response_data)
Based on get-param fields (which is list) I fill response_data data with some calculations, different for each CounterFilters.value .
I'm wondering, if there is a way to avoid this big amounts of ifs ?
Solution
You can shift logic to the TextChoices
function:
class CounterFilters(TextChoices):
publications_total = 'publications-total'
publications_free = 'publications-free'
publications_paid = 'publications-paid'
comments_total = 'comments-total'
votes_total = 'voted-total'
def __call__(self, *args, **kwargs):
return getattr(self, f'get_{self.name}')(*args, **kwargs)
def get_publications_total(self, request):
return 42
def get_publications_free(self, request):
return 14
def get_publications_paid(self, request):
return 25
def get_comments_total(self, request):
return 1337
def get_votes_total(self, request):
return 1207
where you thus can fill in more sophisticated functions for the the get_foo
methods.
Then we can work with:
class SomeView:
def get(self, request, format=None):
user = request.user
response_data = []
if "fields" in request.query_params:
fields = request.GET.getlist('fields')
for field in fields:
try:
_filter = CounterFilter(field)
except ValueError:
pass
else:
response_data.append(
{'type': field, 'count': _filter(request)}
)
return Response(response_data)
You of course can work with different parameters to make the calculations.
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.