Home > Net >  Multiple models in a queryset and/or multiple serializers for one View?
Multiple models in a queryset and/or multiple serializers for one View?

Time:10-05

Say I have a Foo model and a Bar model:

# models.py
class Foo(models.Model):
    foo_title = CharField()
   
class Bar(models.Model):
    bar_title = CharField()


# serializers.py
class FooSerializer(serializers.ModelSerializer):

    class Meta:
        model = Foo
        fields = ["foo_title"]

class BarSerializer(serializers.ModelSerializer):
    foo = FooSerializer()

    class Meta:
        model = Bar
        fields = ["bar_title"]

If I want to return a Foo and a Bar model, I have to set up and call two views:

# urls.py
path("foo/<pk>/", FooView.as_view())
path("bar/<pk>/", BarView.as_view())

# views.py
class FooView(generics.RetrieveAPIView):
    serializer_class = FooSerializer
    lookup_field = pk

class BarView(generics.RetrieveAPIView):
    serializer_class = BarSerializer
    lookup_field = pk

And then combine the two data results on my front-end.

Is it possible to create one View that has multiple models in the queryset and/or multiple serializers? How can I make only one call to my API backend to return the data of different serializers with different models?

e.g. Something like

# urls.py
path("foobar/<foo_pk>/<bar_pk>", FoobarView.as_view())

# views.py
class FoobarView(generics.ListAPIView):
    pass

CodePudding user response:

You can use https://github.com/alanjds/drf-nested-routers

pip install drf-nested-routers

Here's an example of use: https://github.com/alanjds/drf-nested-routers#infinite-depth-nesting

CodePudding user response:

I can do this via APIView:

# urls.py
path("foobar/<foo_pk>/<bar_pk>", FoobarView.as_view())

# views.py
class FoobarView(APIView):
    def get(self, request, foo_pk, bar_pk):
        foo = FooSerializer(Foo.objects.get(pk=foo_pk)).data
        bar = BarSerializer(Bar.objects.get(pk=bar_pk)).data
        return Response([foo, bar], status=status.HTTP_200_OK)
  • Related