I was previously using APIViews such as the following:
views.py
class AllProgramsApi(APIView):
def get(self, request):
user = self.request.user
userprograms = Program.objects.filter(user=user)
serializer = ProgramSerializer(userprograms, many=True)
return Response(serializer.data)
here's my model:
class Program(models.Model):
program_name = models.CharField(max_length=50)
program_description = models.CharField(max_length=250)
cycles = models.ManyToManyField(Cycle)
is_favourite = models.BooleanField(default="False")
user = models.ForeignKey(User, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('programs:program', kwargs={'pk': self.pk})
def __str__(self):
return self.program_name
Now I've discovered ModelViewSet, which looks very convenient, but I can't seem to be able to filter for the user as I was previously doing in the APIView.
my attempt at views.py with ModelViewSet is the following and it works but I get all the content and not just the content related to a single user.
class AllProgramsApi(ModelViewSet):
serializer_class = ProgramSerializer
queryset = Program.objects.all()
How can I tweak the ModelViewSet so that it displays only the content related to the user who sends the request? What is the best method?
Thanks.