Home > Mobile >  How to filter a queryset of Tag objects by current user
How to filter a queryset of Tag objects by current user

Time:08-28

I need to filter tags by current user, in serializers class I can not do request -queryset=TagPrivate.objects.filter(user=self.request.user)

serializers.py

    class DotPrivateSerializer(serializers.ModelSerializer):

        tag = serializers.PrimaryKeyRelatedField(
            many=False,
            queryset=TagPrivate.objects.all() # <-------------------------- filter by user
        )
    
        class Meta:
            model = DotPrivate
            fields = ('id', 'name', 'description', 'lat', 'lon', 'rating', 'link', 'tag')
            read_only_fields = ('id',)

...so is there any way to do it in views.py?

class DotPrivateViewSet(viewsets.ModelViewSet):

    serializer_class = serializers.DotPrivateSerializer
    queryset = DotPrivate.objects.all()
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        """"Return objects for the current authenticated user only"""

        return self.queryset.filter(user=self.request.user)

CodePudding user response:

You can actually get a current use in DRF using this class here . In your case if you want to filter from the serializer you can do this

 class DotPrivateSerializer(serializers.ModelSerializer):
    user_private_tags = TagPrivate.objects.filter(user=serializers.CurrentUserDefault()
    tag = serializers.PrimaryKeyRelatedField(
        many=False,
        queryset=user_private_tags # <-------------------------- filter by user
    )

    class Meta:
        model = DotPrivate
        fields = ('id', 'name', 'description', 'lat', 'lon', 'rating', 'link', 'tag')
        read_only_fields = ('id',)

I belive you are likely to have more than one tag, so you might want to set many=True

...so is there any way to do it in views.py?

The answer is yes, there is away as described here in the doc

class DotPrivateViewSet(viewsets.ModelViewSet):

    serializer_class = serializers.DotPrivateSerializer
    queryset = DotPrivate.objects.all()
    authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        """"Return objects for the current authenticated user only"""
        queryset = self.queryset
        query_set = queryset.filter(user=self.request.user)
        return query_set

Now it is up to you what to go with now.

  • Related