1👍
✅
You should rearrange your code so that you only split the string and filter the queryset if the field is in the querystring.
Since you are only ever accessing the first item in the list, you might as well use get
instead of getlist
.
def filter_queryset(self, queryset):
des = self.request.GET.get("des")
if des is not None:
des_ids = des.split(',')
queryset = queryset.filter(des__in=des_ids)
gender = self.request.GET.get("gender")
if gender is not None:
gender_ids = gender.split(',')
queryset = queryset.filter(gender__in=gender_ids)
return queryset
If you had more than two fields, you could cut down on duplicated code by looping through the list of fieldnames:
def filter_queryset(self, queryset):
for fieldname in ("des", "gender"):
value = self.request.GET.get(fieldname)
if value is not None:
ids = value.split(',')
queryset = queryset.filter(**{'%s__in' % fieldname: ids})
return queryset
Source:stackexchange.com