0

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?

Vinay
  • 699
  • 4
  • 22

1 Answers1

0

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)
Ehsan Nouri
  • 1,990
  • 11
  • 17
  • Well this ensures that the user cannot access another user's books but does it also ensure that a user cannot edit another user's book? – Vinay Oct 25 '18 at 08:22
  • Yes, your view calls the `get_object` method for finding the book that is requsted by user when editing, deleting or retrieving. and `get_object` search for the instane amoung the qureyset returned by the `get_queyset` method. – Ehsan Nouri Oct 25 '18 at 08:30