I tried to create a question filtering function dependent on values from request: question_type and situation. If both predicates provided, I want Questions filterd by both values. If only one of them - I want Questions filtered by provided filter only.
However, no matter what filter values I send in question_type or situation arguments, all questions are returned, no filtering.
models.py
class Question(models.Model):
TYPES_CHOICES = [
("LAWYER","LAWYER"),
("REPAIRMAN","REPAIRMAN"),
]
SITUATION_CHOICES = [
("in","IN"),
("wait","WAIT"),
("closed","CLOSED")
]
question_type = models.CharField(max_length=255,choices=TYPES_CHOICES,default="LAWYER")
title = models.CharField(max_length=255)
description = models.TextField()
image = models.ImageField(upload_to="question_images/",blank=True,null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
situation = models.CharField(max_length=20,choices=SITUATION_CHOICES,default="in")
views.py
class TypeView(ListAPIView):
serializer_class = QuestionSerializer
def get_queryset(self):
qs = Question.objects.all()
question_type = self.request.query_params.get('question_type')
situation = self.request.query_params.get('situation')
if question_type and situation:
qs = qs.filter(question_type=question_type, situation=situation)
elif question_type:
qs = qs.filter(question_type=question_type)
elif situation:
qs = qs.filter(situation=situation)
return qs
urls.py
path('search/<str:question_type>/<str:situation>/', views.TypeView.as_view(), name='filtered-question'),
query_paramsare these things:search?question_type=a&situation=b%20c- arguments after?. You're not using query params thus.query_paramsis always empty. Params from url_pattern are stored inkwargssee the docs