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
CodePudding user response:
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
CodePudding user response:
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)