Django: Serializing a list of multiple, chained models

2024/9/18 16:01:26

Given two different models, with the same parent base class. Is there any way, using either Django Rest Framework Serializers or serpy, to serialize a chained list containing instances of both the child models?

Given some example models:

class BaseModel(models.Model):created_at = models.DateField()class Meta:abstract = Trueclass ChildModel1(BaseModel):field_one = models.TextField()class ChildModel2(BaseModel):field_two = models.TextField()

And 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 method for chaining the models is taken from the answer to this question.

With my current attempts I get a quite obvious error saying something like:

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

I know it is not the best practice to mix two models with some different fields, but in my case I thought it necessary.

Some examples of serializers I have 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)
Answer

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

class Model1Serializer(serializers.Serializer):...class Model2Serializer(serializers.Serializer):...class SummarySerializer(serializers.Serializer):""" Serializer that renders each instance with its own specific serializer """@classmethoddef get_serializer(cls, model):if model == Model1:return Model1Serializerelif model == Model2:return Model2Serializerdef to_representation(self, instance):serializer = self.get_serializer(instance.__class__)return serializer(instance, context=self.context).data

This will work for any models, not only for childs of one class.

https://en.xdnf.cn/q/72408.html

Related Q&A

Formatting cells in Excel with Python

How do I format cells in Excel with python?In particular I need to change the font of several subsequent rows to be regular instead of bold.

What is the legality of scraping YouTube data? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in the help center.Cl…

Numpy: fast calculations considering items neighbors and their position inside the array

I have 4 2D numpy arrays, called a, b, c, d, each of them made of n rows and m columns. What I need to do is giving to each element of b and d a value calculated as follows (pseudo-code):min_coords = m…

How to see all the databases and Tables in Databricks

i want to list all the tables in every database in Azure Databricks. so i want the output to look somewhat like this: Database | Table_name Database1 | Table_1 Database1 | Table_2 Database1 | Table_3 D…

How to get transparent background in window with PyGTK and PyCairo?

Ive been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I cant get it to work.Ive tried a…

concurrent.futures.ThreadPoolExecutor doesnt print errors

I am trying to use concurrent.futures.ThreadPoolExecutor module to run a class method in parallel, the simplified version of my code is pretty much the following: class TestClass:def __init__(self, sec…

How to write a Dictionary to Excel in Python

I have the following dictionary in python that represents a From - To Distance Matrix.graph = {A:{A:0,B:6,C:INF,D:6,E:7},B:{A:INF,B:0,C:5,D:INF,E:INF},C:{A:INF,B:INF,C:0,D:9,E:3},D:{A:INF,B:INF,C:9,D:0…

How can I check pooled connections in SQLAlchemy before handing them off to my application code?

We have a slightly unreliable database server, for various reasons, and as a consequence sometimes the database connections used by my application vanish out from under it. The connections are SQLAlch…

pandas list of dictionary to separate columns

I have a data set like below:name status number message matt active 12345 [job: , money: none, wife: none] james active 23456 [group: band, wife: yes, money: 10000] adam in…

Where is console input history stored on Python for Windows?

Good afternoon,The QuestionIs there a particular spot that the entries are stored, or is it just a local set of stored variables, for the windows version of Python?The ContextI am curious about where …