I wish to create an API that allows a user to access/update details of Books only uploaded by them. The user should not have permission to access/update a book that has been created by someone else.
This is my models.py
:
from django.contrib.auth.models import User
class Project(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
name = models.CharField(max_length=200)
class Book(models.Model):
project = models.ForeignKey(Project,on_delete=models.CASCADE)
name = models.CharField(max_length=200)
total_pages = models.IntegerField()
This is my serializers.py
:
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
Here is my views.py
:
class BookDetails(generics.RetrieveUpdateDestroyAPIView):
serializer_class = BookSerializer
queryset = Book.objects.all()
How do I modify the views.py
such that the user can only access/update books created by him?
use get_queryset
method in your view and filter the queryset based on the authenticated user:
class BookDetails(generics.RetrieveUpdateDestroyAPIView):
serializer_class = BookSerializer
def get_queryset(self):
user = self.request.user
return Book.objects.filter(project__user=user)