Search code examples
pythondjangodjango-rest-framework

How i can to filter queryset by current user in django rest framework


class SalonCarDetailsSerializer(serializers.ModelSerializer):

    salon = PrimaryKeyRelatedField(queryset=Salon.objects.filter(owner=?))

    class Meta:
        model = SalonCarDetails
        fields = ["salon", "car", "price", "number_of_cars"]

CurrentUserDefault() doesn't works


Solution

  • Well, you could write your own PrimaryKeyRelated field like that:

    class SalonKeyRelatedField(serializers.PrimaryKeyRelatedField):
        def get_queryset(self):
            qs = super().get_queryset()
            request = self.context.get('request')
            qs = qs.filter(owner=request.user)
            return qs
    

    This will be called only on POST and PUT requests. You can then include it in your serializer

    salon = SalonKeyRelatedField()
    

    don't forget to include salon in your fields