I have this json response from my customer api based on django rest framework.
When I hit api
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