简体   繁体   中英

KeyError: 'request' in DRF with ModelSerializer

serializers.py

from rest_framework import serializers
from .models import Flight, Segment, Airport


class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        fields = self.context['request'].query_params.get('fields')
        if fields:
            fields = fields.split(',')
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)


class SegmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Segment
        fields = (  # TODO - Could be __all__ if no fine tuning
            'id', 'flight_id', 'dep_code', ...
        )


class FlightSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer):
    segments = SegmentSerializer(many=True, source='segment_set')

    class Meta:
        model = Flight
        fields = (  # TODO - Could be __all__ if no fine tuning
            'id', 'dep_air', 'dest_air', ...
        )


class AirportSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer):
    dep_air = FlightSerializer(many=False, source='dep_air_airport')

    class Meta:
        model = Airport
        fields = ('iata_code', 'name', 'continent', 'iso_country',)

I get the following error when starting up the server:

  File "/Users/me/PycharmProjects/fly_baby/flight_data/serializers.py", line 55, in AirportSerializer
    dep_air = FlightSerializer(many=False, source='dep_air_airport')
  File "/Users/me/PycharmProjects/fly_baby/flight_data/serializers.py", line 15, in __init__
    fields = self.context['request'].query_params.get('fields')
KeyError: 'request'

The goal is to have the flights nested under the airports, or vice versa but it doesn't seem possible when I used the DynamicFieldsModelSerializer mixin. The init asks for the self.context['request'] which doesn't exist for the following line

dep_air = FlightSerializer(many=False, source='dep_air_airport')

I believe I'm somehow meant to pass the context along, but I don't know how that's possible given my generics-heavy setup.

Extra code::

views.py

class AirportFlightViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = FlightSerializer

    def get_queryset(self):
        return Flight.objects.filter(flight=self.kwargs['airport_pk'])

urls.py

router = DefaultRouter()
router.register(r'flights', views.FlightViewSet)
router.register(r'segments', views.SegmentViewSet)
router.register(r'airports', views.AirportViewSet)

flights_router = routers.NestedSimpleRouter(router, r'flights', lookup='flight')
flights_router.register(r'segments', views.FlightSegmentViewSet, basename='flight-segments')

airports_router = routers.NestedSimpleRouter(router, r'airports', lookup='airport')
airports_router.register(r'flights', views.AirportFlightViewSet, basename='airport-flights')

urlpatterns = [
    path('', views.index),
    path('api/', include(router.urls)),
    path('api/', include(flights_router.urls)),
    path('api/', include(airports_router.urls)),
]

You can edit DynamicFieldsModelSerializer to not depend on the context being present so it can be constructed without it by using .get() :

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        request = self.context.get('request')

        if request:
            fields = request.query_params.get('fields')
            if fields:
                ...  # code as before

Note, however, that when used like this the child serializer ( FlightSerializer in this case), will always have all fields applied. This makes sense, however, because on a request for airport you'd expect the fields param to affect the fields of the airport, not of the flights.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM