rsinger86/drf-flex-fields

Passing context to serializer with `request` param causes `AttributeError` on `query_params`

Opened this issue · 6 comments

When you create a Serializer like this:

MySerializer(data, context={'request': request})

Then I get the following error:

AttributeError: 'WSGIRequest' object has no attribute 'query_params'

Because drf-flex-fields relies on the query_params that is provided by the HttpRequest wrapper of Django Rest Framework

But if you create a serializer manually, and pass the request object into the context, then we have a regular Django HttpRequest object, which does not contain the query_params property.

The issue can be resolved like this:

from rest_framework.request import Request
from rest_flex_fields import FlexFieldsModelSerializer


class MySerializer(FlexFieldsModelSerializer):

    def __init__(self, *args, **kwargs):

        if (
            'context' in kwargs
            and 'request' in kwargs['context']
            and not hasattr(kwargs['context']['request'], 'query_params')
        ):
            kwargs['context']['request'] = Request(kwargs['context']['request'])

        super().__init__(*args, **kwargs)

Maybe we can incorporate this in some way into drf-flex-field?

What is the point of using a DRF serialier with a standard request?

I mean: you should know when you are in an APIView (or @api_view) or not, if not you should take care of providing the right argument to the serializer.

In my case, I was using the serializer outside of a DRF API view. I like to re-use serializers sometimes for functionality outside the API.

In that case the "fix" is simple:

from rest_framwork.request import Request


...
MySerializer(data, context={'request': Request(request)})

Since you are using this outside rest framework "middleware" I belive it is normal that you should provide the appropriated changes.

Aha, fair enough. Although usually serializers work fine with Django request objects. Just not when using FlexFields. So when you're introducing FlexFieldsModelSerializer or FlexFieldsSerializerMixin in your code, you can suddenly have this issue, and you would need to figure out what the problem is and apply the fix to potentially multiple spots in your code. People might think that FlexFields just doesn't work for their use-case, or with their version of Django / DRF.

But I understand your reasoning as well. We could also check if query_params exists, and if not, raise a custom exception with a descriptive error message so the user understands it should wrap the Django Request object in a Rest Framework Request object.

To solve that the easiest fix would be to make flex-fields use request.GET instead of request.query_params (which is just an alias property).

Aha yeah that sounds like a good idea. Then it doesn't have a dependency on DRF request objects, and it can just work with common Django request objects.