Home > other >  how to Serialize multiple objects in Django
how to Serialize multiple objects in Django

Time:05-23

I have 2 models for admin and member positions and I would like to get both of the models in one API call to fetch the data on my front end. How can I achieve this?

class ClinetAdminPosition(models.Model):
    name = models.CharField(max_length=128, null=True)
    company = models.ForeignKey(
        to="Company", on_delete=models.CASCADE, related_name="admin_positions", null=True
    )
    modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True)
    created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False)

    def __str__(self):
        return f"{self.name}"

class ClinetMangerPosition(models.Model):
    name = models.CharField(max_length=128, null=True)
    company = models.ForeignKey(
        to="Company", on_delete=models.CASCADE, related_name="manger_positions", null=True
    )
    modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True)
    created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False)

    def __str__(self):
        return f"{self.name}"

I want to get both models' data from 1 API request

to be like this:

[
  {
    "admin_positions": [
      {
        "name": "test",
        "company": 1
      },
      {
        "name": "test2",
        "company": 1
      },
      {
        "name": "test3",
        "company": 1
      }
    ],
    "manger_position": [
      {
        "name": "test",
        "company": 1
      },
      {
        "name": "test2",
        "company": 1
      },
      {
        "name": "test3",
        "company": 1
      }
    ]
  }
]

CodePudding user response:

You can do something like this.

**This is your serializers classes **

 class ClinetMangerPositionSerializer(ModelSerializer)
      
      clas Meta:
         model = ClinetMangerPosition

         fields = ['name','company']

class ClinetAdminPositionSerializer(ModelSerializer):
      
      class Meta:
          model = ClinetAdminPosition
          fields = ['name','company']

This will be your views class to display data.

from rest_framework.views import APIView
from . import serializers
from rest_framework.response import Response

class ViewName(APIView):
   
   def get(self, request):
      admin = ClinetAdminPosition.objects.all()
      manager = ClinetMangerPosition.objects.all()
      
      res :{
          "admin_positions": serializers.ClinetAdminPositionSerializer(admin, many=True).data
          "manager_positions":serializers.ClinetMangerPositionSerializer(manager, many-True).data
      }

      return Response(res)

something like this,

CodePudding user response:

Let me know if you got any doubt

class ClinetMangerPositionSerializer(ModelSerializer)
      
      clas Meta:
         model = ClinetMangerPosition

         fields = ['name','company']

class ClinetAdminPositionSerializer(ModelSerializer):
      
      class Meta:
          model = ClinetAdminPosition
          fields = ['name','company']
class CompanySerializer(MOdelSerializer): 
      manger_position = ClinetAdminPositionSerializer(many=True,source 
         ='clinetmangerposition')
      admin_position = ClinetAdminPositionSerializer(many=True,source 
                  ='clinetadminposition')
      class Meta:
         model= Company
         fields = ['manger_position','admin_position']
      
  • Related