Django: Serialize a list of multiple linked models


Waldemar Edward Sandel Rolfson

Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy?

Given some example models:

class BaseModel(models.Model):
   created_at = models.DateField()

   class Meta:
       abstract = True


class ChildModel1(BaseModel):
    field_one = models.TextField()


class ChildModel2(BaseModel):
    field_two = models.TextField()

There is also an example view:

def get(self, request):

    q1 = ChildModel1.objects.all()
    q2 = ChildModel2.objects.all()

    chained_list = sorted(
        chain(q1, q2),
        key=attrgetter('created_at'))

    serializer = BaseModelSerializer(chained_list, many=True)

The way to link the models comes from the answer to this question .

With my current attempts, I get a pretty obvious error like:

AttributeError: 'ChildModel1' object has no attribute 'field_two'

I know it's not best practice to combine both models with different domains, but in my case I think it's necessary.

Some examples of serializers I've tested:

First example:

class BaseModelSerializer(serializers.ModelSerializer):

   class Meta:
       model = BaseModel

Second example:

class BaseModelSerializer(serpy.Serializer):
   created_at = serpy.StrField()

   field_one = serpy.StrField(required=False)
   field_two = serpy.StrField(required=False)
yeast

You can define serializers that will combine two or more serializers based on the model:

class Model1Serializer(serializers.Serializer):
    ...

class Model2Serializer(serializers.Serializer):
    ...

class SummarySerializer(serializers.Serializer):
    """ Serializer that renders each instance with its own specific serializer """

    @classmethod
    def get_serializer(cls, model):
        if model == Model1:
            return Model1Serializer
        elif model == Model2:
            return Model2Serializer

    def to_representation(self, instance):
        serializer = self.get_serializer(instance.__class__)
        return serializer(instance, context=self.context).data

This will work on any model, not just a class of children.

Related


Django: Serialize a list of multiple linked models

Waldemar Edward Sandel Rolfson Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy? Given some example models:

Django: Serialize a list of multiple linked models

Waldemar Edward Sandel Rolfson Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy? Given some example models:

Django: Serialize a list of multiple linked models

Waldemar Edward Sandel Rolfson Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy? Given some example models:

Django: Serialize a list of multiple linked models

Waldemar Edward Sandel Rolfson Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy? Given some example models:

Django: Serialize a list of multiple linked models

Waldemar Edward Sandel Rolfson Given two different models, they have the same parent base class. Is it possible to serialize a linked list containing instances of two child models using the Django Rest Framework serializer or serpy? Given some example models:

serialize data from multiple models django

Matt Is it possible to serialize data from multiple models in Django? For example, my code below will currently provide JSON of data from my "build" model. serializer.py class buildStatsAPI_serializer(serializers.ModelSerializer): class Meta: field

Django serialize multiple models in a single view

seagulls Here is the scenario, I have two models Offre and Recruiteur class Recruteur(models.Model): [...] entrepriseName = models.CharField(max_length=50) [...] class Offre(models.Model): [...] idRecruteur = models.ForeignKey(

serialize data from multiple models django

Matt Is it possible to serialize data from multiple models in Django? For example, my code below will currently provide JSON of data from my "build" model. serializer.py class buildStatsAPI_serializer(serializers.ModelSerializer): class Meta: field

Put multiple Django models into a list

Enns and Bees I have a MySQL database with four related tables: project, unit, unit_equipment and equipment. A project can have many units; a unit can have many related equipment entries. A unit can only belong to one project, but there is a many-to-many relat

Put multiple Django models into a list

Enns and Bees I have a MySQL database with four related tables: project, unit, unit_equipment and equipment. A project can have many units; a unit can have many related equipment entries. A unit can only belong to one project, but there is a many-to-many relat

Put multiple Django models into a list

Enns and Bees I have a MySQL database with four related tables: project, unit, unit_equipment and equipment. A project can have many units; a unit can have many related equipment entries. A unit can only belong to one project, but there is a many-to-many relat

Put multiple Django models into a list

Enns and Bees I have a MySQL database with four related tables: project, unit, unit_equipment and equipment. A project can have many units; a unit can have many related equipment entries. A unit can only belong to one project, but there is a many-to-many relat

Put multiple Django models into a list

Enns and Bees I have a MySQL database with four related tables: project, unit, unit_equipment and equipment. A project can have many units; a unit can have many related equipment entries. A unit can only belong to one project, but there is a many-to-many relat

DRF - serialize multiple models

Dibu Escobedo please help! How can I get this JSON { "value": 9998, "startDate": "01-03-2019T06:59", "endDate": "31-03-2019T23:59", "days": 11111111, "name": "Juices", "Stores": [ 921, 923 ] } Because, with my code I only r

DRF - serialize multiple models

Dibu Escobedo please help! How can I get this JSON { "value": 9998, "startDate": "01-03-2019T06:59", "endDate": "31-03-2019T23:59", "days": 11111111, "name": "Juices", "Stores": [ 921, 923 ] } Because, with my code I only r

DRF - serialize multiple models

Dibu Escobedo please help! How can I get this JSON { "value": 9998, "startDate": "01-03-2019T06:59", "endDate": "31-03-2019T23:59", "days": 11111111, "name": "Juices", "Stores": [ 921, 923 ] } Because, with my code I only r

Serialize multiple models in a single view

musashiXXX Here is the scene: I have two models; FileObj and DirObj. class DirObj(models.Model): [...] parent = models.ForeignKey('self') [...] class FileObj(models.Model): [...] parent = models.ForeignKey(DirObj) [...] I have the fol

Serialize two different models with Django

Eliel Van Hojman I have two models Propertyand PropertyImage. Property holds all data, PropertyImage is only used to allow unlimited number of image uploads. class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images')

Serialize objects instead of models in Django

Kilogram I want to serialize an object, but the object is not a model, just a regular class. what should I do class Test: foo = [] bar = 1 a = tt() class tt a = "Test" Daniel Rothman Are you sure you want to be an object at all? Looks like a n

Serialize two different models with Django

Eliel Van Hojman I have two models Propertyand PropertyImage. Property holds all data, PropertyImage is only used to allow unlimited number of image uploads. class PropertyImage(models.Model): property = models.ForeignKey(Property, related_name='images')