python - Serializer field filtering in Django Rest Framework? -


in serializers.py can do:

class boxserializer(serializers.modelserializer):     user = serializers.readonlyfield(source='user.email')     playlist = primarykeyrelatedfield(allow_null=true, source='playlist.name',         queryset=playlist.objects.all(), required=false)      class meta:         model = box 

i can (hardcoded, works):

playlist = primarykeyrelatedfield(allow_null=true, source='playlist.name',             queryset=playlist.objects.filter(user=user.objects.get(id=4)), required=false) 

i'm new @ this, , wondering if there way can request.user via method or something this:

(i know incorrect, serves point across):

playlist = primarykeyrelatedfield(allow_null=true, source='playlist.name',             queryset=playlist.objects.filter(user=request.user), required=false) 

or can this(again incorrect):

playlist = primarykeyrelatedfield(allow_null=true, source='playlist.name',         queryset='get_playlists', required=false)  def get_playlists(self):     user = self.context['request'].user     return playlist.objects.filter(user=user) 

try this:

class boxserializer(serializers.modelserializer):     # ...      def __init__(self, *args, **kwargs):         user = kwargs['context']['request'].user          super(boxserializer, self).__init__(*args, **kwargs)         self.fields['playlist'].queryset = playlist.objects.filter(user=user) 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -