[Answered ]-Django REST Framework serializer with different models

0👍

You need to make a union on the querysets:

query_union = query1 | query 2

And you need a custom serializer for the fields of that union. Or if the union fields are all the same from any of the models, possibly use those model’s modelserializer, but haven’t tested that one.

👤Wtower

2👍

The most important thing here is that you shouldn’t be having three different models here. If they are storing the same data, there should be only one model. To have three models means every time you need to execute a statement you need to precede that with a IF ELIF ELSE which is far from DRY. Not to mention the fact that you need to do a UNION as suggested by Wtower in his answer

Merge the models.

👤e4c5

0👍

dataA = ASerializer(queryset_A, many=True).data
dataB = BSerializer(queryset_B, many=True).data
dataC = CSerializer(queryset_C, many=True).data

just

return Response(data={‘dataA ‘: dataA , ‘dataB ‘: dataB ,’dataC ‘: dataC })

If you want return a list,the item is {‘a’:a,”b’:’b,’c’:c},you should declare you relation between a,b,c and can filter b and c with a.If so,i will write an example for you.

👤Ykh

Leave a comment