drf-nested-routers icon indicating copy to clipboard operation
drf-nested-routers copied to clipboard

Nested router and APIRequestFactory context

Open aleehedl opened this issue 7 years ago • 6 comments

I have the following routes and CRUD views working nicely using DRF nested routers:

  • /pages/
  • /pages/<page_id>/
  • /pages/<page_id>/menus/

In my menu serializer I use the page_id from the route to fetch the corresponding page:

class MenuSerializer(serializers.ModelSerializer):
    def to_internal_value(self, data):
        resp = super().to_internal_value(data)
        resp['page'] = Page.objects.get(pk=self.context['view'].kwargs['page_id'])
        return resp

In normal use this works fine - context['view'].kwargs contains the page_id as expected.

Now, I'm trying to write integration tests using rest_framework.test.APIRequestFactory like this:

request = APIRequestFactory().post(
    f'/pages/{page_id}/menus/?format=json', menu_data, format='json'
)
response = MenuViewSet.as_view({'post': 'create'})(request)

Now, the MenuSerializer.to_internal_value method fails because page_id does not exist in the view context.

How should I proceed?

aleehedl avatar Aug 10 '18 06:08 aleehedl

No idea. Sorry. Do you think APIRequestFactory is misbehaving?

Question: Is this related to Nested Routers? I saw no relation with it, just with Django Rest Framework. Maybe this issue should be opened there.

alanjds avatar Aug 10 '18 18:08 alanjds

I haven't had time to look into the DRF nested router`s codebase much but I suppose it's a question of who's business it is to but the subroute into the view context. Maybe the APIRequestFactory could be subclassed in DRF nested router's code to make testing easier?

aleehedl avatar Aug 12 '18 04:08 aleehedl

What I mean is: Your exemple does not involve a nested route. So, do it work in a scenario without drf-nested-routers?

If yes, we can bake a test and debug up to the point it starts to "not work as expected". If not, you should file an issue on https://github.com/encode/django-rest-framework, not here.

alanjds avatar Aug 13 '18 18:08 alanjds

Sorry. I just realised that the MenuSerializer is the nested resource.

Let me think a bit then.

alanjds avatar Aug 13 '18 19:08 alanjds

@aleehedl Did you come to the resolution of this issue? Asking since I am also facing this issue.

GauravWaghmare avatar Feb 27 '20 14:02 GauravWaghmare

Not really @GauravWaghmare. I never went to this road of usage. Sorry.

Having a minimal automated test expressing the failing behavior would help I guess.

alanjds avatar Feb 27 '20 17:02 alanjds