Home > Software design >  In Django Rest Api, how do you return only the Items the owner uploaded
In Django Rest Api, how do you return only the Items the owner uploaded

Time:10-12

The Viewset def list looks like this:

class ThreeDimensionalModelViewSet(viewsets.ViewSet):
    serializer_class = ThreeDimensionalModelSerializer
    queryset = ThreeDimensionalModel.objects.all()
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def list(self, request):
        models = ThreeDimensionalModel.objects.all()
        serializer = ThreeDimensionalModelSerializer(models, many=True)
        print(request.user.id)
        return Response(serializer.data)

The serializer looks like this:

class ThreeDimensionalModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ThreeDimensionalModel
        fields = ['File', 'Uploaded', 'Owner', 'Previous', 'SharedWithUser']
        read_only_fields = ['Owner']

The model looks like this:

class ThreeDimensionalModel(models.Model):
    File = models.FileField(upload_to='models')
    Owner = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, related_name='Owner')
    Uploaded = models.DateTimeField(auto_now_add=True)
    Previous = models.ForeignKey("self", on_delete=models.SET_NULL, default=None, null=True)
    SharedWithUser = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='SharedWithUser')

When a user requests models at /api/models it should only show the models that are the same owner Id as his.

CodePudding user response:

If no additional data is sent with that request then obviously you can't filter by user.

The straightforward way to do it is that for logged in users the cookie will contain user information such as userId.

When your endpoint recognizes the user who made the requested is logged in, it will use that as the filter for the query instead of all() as seen in the Django docs https://docs.djangoproject.com/en/3.2/topics/db/queries/#retrieving-specific-objects-with-filters

To summarize - if the user is not logged in (or supplies the information as part of the request in some way) then the request is anonymous and there is no way to know who made it

  • Related