0

I have this json response from my customer api based on django rest framework.

When I hit api

http://localhost:8000/api/customers

I receive following response

[
 {
    'name': 'Daniel',
    'group': 'BK',
    'user_id': 102,
    'user_details': {
        'username': 'dan1',
        'active': true,
    }
 },
 {
    'name': 'John',
    'group': 'BK',
    'user_id': 103,
    'user_details': {
        'username': 'john1',
        'active': true,
    }
 }
]

Now I need to filter record whose username=john1, how do I do that?

I have tried using this in my customer viewset by defining filter backend

filter_fields = ('user_details__username',)

and tried hitting the api as

http://localhost:8000/api/customers?user_details__username=john1

but it gives error as

'Meta.fields' contains fields that are not defined on this FilterSet: user_details__username

Its happening because user_details is not the field of my customer serializer, its basically SerializerMethodField which manipulates user information to display under customer api.

Here is my customer serializer

class CustomerSerializer(serializers.HyperlinkedModelSerializer):
    user_details = serializers.SerializerMethodField('get_serialized_target_object')

    class Meta:
        model = Customer
        fields = '__all__'        

    def get_serialized_target_object(self, obj):
        usr_id = obj.user_id
        if usr_id:
            instance = User.objects.filter(pk=usr_id)
            if instance:
                instance = instance[0]
                return UserSerializer(instance=instance).data

        else:
            return None

and here is my viewset

class CustomerViewSet(viewsets.ModelViewSet):
   queryset = Customer.objects.all()
   serializer_class = CustomerSerializer
   filter_fields = ('user_details__username',)

Please help me how do I filter my record from customer api with username=john1

1 Answer 1

1

You should not use SerializerMethodField.

Try the serializer below:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'active',)


class CustomerSerializer(serializers.ModelSerializer):
    user_details = UserSerializer(many=True)

    class Meta:
        model = Customer
        fields = '__all__'

Then you can define your field as filter_fields = ('user_details__username',)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.