serializers - filter by a current user

Viewed 18

When creating a Dot object I want to choose between tags that belongs to current User

    class DotSerializer(serializers.ModelSerializer):

        tag = serializers.PrimaryKeyRelatedField(
            queryset=Tag.objects.all()
         )

I tried few ways but all of them give me an error

    current_user = serializers.SerializerMethodField()

    def get_current_user(self, obj):
         request = self.context.get('request', None)
         if request:
             return request.user.id

    tag = serializers.PrimaryKeyRelatedField(
        queryset=TagPrivate.objects.filter(user=current_user)
    ) #TypeError: Field 'id' expected a number but got SerializerMethodField()

this one above two

    tag = serializers.PrimaryKeyRelatedField(
        queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault())
    )#TypeError: Field 'id' expected a number but got CurrentUserDefault()
1 Answers

Try to override serializer's __init__ method:

class DotSerializer(serializers.ModelSerializer):

    tag = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all()
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        request = self.context.get('request', None)
        self.fields['tag'].queryset=TagPrivate.objects.filter(user=request.user.id)
Related