简体   繁体   中英

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

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')
        return qs

then you can filter qs by request.user, 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

I wish I could see your views.py, but anyway I make some assumptions about it and put it in the class implementation scenario.

#
### views.py
#

# Django native libraries
from rest_framework.serializers import Serializer
from rest_framework import viewsets, mixins, status
from django.db.models import Q

# your serializer and model
from .serializers import YourSalonCarSerializer
from .models import SalonCarDetails

class YourCustomViewSet(mixins.RetrieveModelMixin, 
                    mixins.ListModelMixin,
                    mixins.UpdateModelMixin, 
                    mixins.DestroyModelMixin,
                    viewsets.GenericViewSet):

    queryset = SalonCarDetails.objects.all()
    serializer_class = YourSalonCarSerializer

    def get_queryset(self):
        if self.request.user.is_anonymous:
            return []

        lookups = Q(user=self.request.user)
        queryset  = self.queryset.filter(lookups)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM