[Answered ]-Django Rest Api filter field's select options based on request.user

0👍

I removed the get_serializer_context and instead updated my codes to this.

serializer = EditCampaignSerializer(queryset, many=True, context={'request': self.request})

Now, the request is passed to the serializer.

2👍

Not sure what your models look like, but something like this will work:

views.py:

class EditCampaignViewSet(ModelViewSet):
    ...

    def get_serializer_context(self):
        return {'request': self.request}

serializers.py:

class EditCampaignSerializer(serializers.ModelSerializer):

    class Meta:
        ...
        ...

    def __init__(self, *args, **kwargs):
        super(EditCampaignSerializer, self).__init__(*args, **kwargs)
        user = self.context['request'].user
        self.fields['clist'] = ChoiceField(choices=ContactList.objects.filter(company__user=user))
👤Badjio

Leave a comment