Home > OS >  DRF - how to concatenate two different models in one .json api?
DRF - how to concatenate two different models in one .json api?

Time:02-17

I have task to output to different models in one .json file

So I need at the end two different models look like this on one api page: http://127.0.0.1:8000/cat_dog_api/

My goal output:

[
    {
        "dog_big": "Mastiff",
        "dog_small": "Terrier",
        "same_line": "different words 1",

    },
    {
        "cat_big": "Singapura",
        "cat_small": "Maine Coon",
        "same_line": "different words 2",
    }
]

Example models:

class Cat(models.Model):
    cat_big = models.CharField(max_length=300)
    cat_small = models.CharField(max_length=300)
    same_line = models.CharField(max_length=300)


class Dog(models.Model):
    dog_big = models.CharField(max_length=300)
    dog_small = models.CharField(max_length=300)
    same_line = models.CharField(max_length=300)

I found out how to concatenate models with "chain" in one queryset

Views.py:

from itertools import chain

class Whole_test(generics.ListAPIView):
    serializer_class = Cat_dog_Serializer

    def get_queryset(self):
        return list(chain(Cat.objects.all(), Dog.objects.all()))

But I'm stuck when time comes to serializer, I have to choose one model with serialiser,

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

but in this case it doesn't serealize my Dog model from my queryset

Is there a way to achieve my goal, maybe a different approach from mine?

CodePudding user response:

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

CodePudding user response:

I found solution:

pip install django-rest-multiple-models

settings.py

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

Views.py

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

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"),
  • Related