[Answered ]-DRF โ€“ how to concatenate two different models in one .json api?

0๐Ÿ‘

โœ…

I found solution:

pip install django-rest-multiple-models

settings.py

INSTALLED_APPS = (
    ....
    'drf_multiple_model',
)

Views.py

from drf_multiple_model.views import FlatMultipleModelAPIView

class Dog_cat_view_api(FlatMultipleModelAPIView):
    pagination_class = None
    add_model_type = False
    querylist = [
        {'queryset': Dog.objects.all(), 'serializer_class': Dof_Serializer},
        {'queryset': Cat.objects.all(), 'serializer_class': Cat_Serializer},
    ]

here is anothere view in which i can retrive data from GET/POST/DELETE/PUT requests, which you can use for filtering

class Dog_cat_view_api(ObjectMultipleModelAPIView):
    def get_querylist(self):

        #this is a user(header Authorization:token 123123)
        user = self.request.user 
        #this is data (in body(form-data))
        data = self.request.data

        querylist = [
            {'queryset': Dog.objects.all(), 'serializer_class': Dof_Serializer},
            {'queryset': Cat.objects.all(), 'serializer_class': Cat_Serializer},
        ]
        return querylist

Serializer.py

class Dog_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Dog
        fields = '__all__'

class Cat_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Cat
        fields = '__all__'

urls.py

path('cat_dog_api/', views.Dog_cat_view_api.as_view(), name="cat_dog_api"),
๐Ÿ‘คoruchkin

1๐Ÿ‘

You need nested serializers inside Cat_dog_Serializer.

class CatSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cat
        fields = '__all__'

class DogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dog
        fields = '__all__'

class Cat_dog_Serializer(serializers.Serializer):
    cat = CatSerializer()
    dog = DogSerializer()

    class Meta:
        fields = ["cat", "dog",]

You can read more here: https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

๐Ÿ‘คBartosz Stasiak

Leave a comment