[Python] how to Serialize multiple objects in Django

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    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
    }
    ]
    }
    ]

    Continue reading...

Compartilhe esta Página