Skip to content

Passing context to serializer with request param causes AttributeError on query_params #128

@gitaarik

Description

@gitaarik

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions