Saša Kalaba
Saša Kalaba

Reputation: 4411

Serializer field filtering in Django Rest Framework?

In my serializers.py i 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 even do something like this (hardcoded, but works):

playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
            queryset=Playlist.objects.filter(user=User.objects.get(id=4)), required=False)

I'm new at this, and I was wondering if there is a way I can request.user via some method or something that will do something like this:

(I know this is incorrect, this serves only to get my point across):

playlist = PrimaryKeyRelatedField(allow_null=True, source='playlist.name',
            queryset=Playlist.objects.filter(user=request.user), required=False)

Or can I do something like 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)

Upvotes: 2

Views: 3057

Answers (2)

Rex Salisbury
Rex Salisbury

Reputation: 478

This may work:

class UserSerializer(serializer.ModelSerializer):
    email = serializes.EmailField()
    playlists = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    box = serializer.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = User

Depending on your models and their relationships, you will have to use some form of nested serializers and/or related fields. It may not all fit neatly into one Serializer. Read more about Serializers and there relationships in the docs.

Upvotes: 0

mariodev
mariodev

Reputation: 15484

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)

Upvotes: 3

Related Questions