Answer the question
In order to leave comments, you need to log in
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')
]
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)
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)
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{},
{},
{}
]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question