Filter on category in django
I was doing the project on Django & react using RestAPI to get into it more deeply. I have a problem with the view part. There are models; Course, CourseCategory.
CourseCategory is about what category a course is related to (which is ForeignKey).
I have list all the courses in one page where a certain category is clicked. But I don't know how to do it in the right way.
Here is my model
class CourseCategory(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
def __str__(self):
return self.title
class Course(models.Model):
category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE, null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=False , blank= False)
brief = models.TextField(null=False , blank= False)
image = models.ImageField(upload_to='img/%y/m/%d', default='img/1.png')
def __str__(self):
return self.name
and here is my view where i tried to write a filter function
class CourseList(generics.ListCreateAPIView):
queryset = Course.objects.all()
serializer_class = CourseSerializer
#permission_classes = [IsAuthenticated]
#authentication_classes = [TokenAuthentication]
def get_queryset2(self):
qs = super().get_queryset()
if 'result' in self.request.GET:
cat = int(self.request.GET['result'])
qs = Course.objects.filter( category=cat )
return qs
when tried to test that by writing the id of the category it's doesn't work like this enter image description here enter image description here
so is there anyone who can help, please
Hi you can implement that in two steps. First you can get the category instance using "cat" then use the category instance to filter the course data. I am not sure what "cat" represents here but I am assuming it is the title of the category.
def get_queryset2(self):
qs = super().get_queryset()
if 'result' in self.request.GET:
cat = int(self.request.GET['result'])
cat_ins = CourseCategory.objects.filter(title=cat)
qs = Course.objects.filter(category=cat_ins)
return qs