W
W
Wondermarin2020-02-09 19:00:53
Django
Wondermarin, 2020-02-09 19:00:53

How to combine multiple models into one serializer?

Hello, I needed to combine several models (4) into one serializer, but there were problems with the implementation.

urls.py

from django.urls import path
from .views import FiltersView

urlpatterns = [
    path('filters/' FiltersView.as_view(), name='Filters')
]


views.py
from rest_framework import views
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from .serializers import FiltersSerializers

class FiltersView(views.APIView):
    def get(self, request, *args, **kwargs):
        filters = {}
        filters['model_1'] = Model1.objects.all()
        filters['model_2'] = Model2.objects.all()
        filters['model_3'] = Model3.objects.all()
        serializer = FiltersSerializers(filters, many=True)
        return Response (serializer.data, status=HTTP_200_OK)


serializers.py
from rest_framework import serializers

class FiltersSerializers(serializers.Serializer):
    model_1 = Model1Serializers(read_only=True, many=True)
    model_2 = Model2Serializers(read_only=True)
    model_3 = Model3Serializers(read_only=True)


But in the output I get:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {},
    {},
    {}
]


What could be the problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question