繁体   English   中英

我如何在 django rest 框架中过滤当前用户的查询集

[英]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() 不起作用

那么,您可以像这样编写自己的 PrimaryKeyRelated 字段:

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

然后你可以通过 request.user 过滤 qs,这只会在 POST 和 PUT 请求时调用。 然后你可以将它包含在你的序列化器中

salon = SalonKeyRelatedField()

不要忘记在您的领域中包括沙龙

我希望我能看到你的 views.py,但无论如何我对它做了一些假设并将其放在 class 实现场景中。

#
### 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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