Django Rest Framework中的Serializer字段过滤?

时间:2016-02-05 17:50:51

标签: python django django-rest-framework

在我的serializers.py中,我可以这样做:

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

我甚至可以做这样的事情(硬编码,但有效):

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

我是新手,我想知道是否有一种方法可以通过某种方法请求。用户可以做类似的事情:

(我知道这是不正确的,这只是为了解释我的观点):

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

或者我可以做这样的事情(再次不正确):

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)

2 个答案:

答案 0 :(得分:3)

试试这个:

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)

答案 1 :(得分:0)

这可能有效:

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

根据您的模型及其关系,您必须使用某种形式的嵌套序列化程序和/或相关字段。它可能并非完全适合一个SerializerRead more about Serializers and there relationships in the docs