I have 5 models with same fields inheriting from a base model. Now for all the five models I am having 5 serializers serializing all the fields for their respective models. An example of the setup is as below
base model
class BaseModel(models.Model):
field 1
field 2
** model 1**
class Model1(BaseModel):
field 3 = models.Charfield(choices=CHOICES)
model 2
class Model 2(BaseModel)
field 3 = models.Charfield(choices=CHOICES)
So field3 is common in both the models but have different choices in them hence are placed in different models and not in the base model.
serializer
class SerialModel1(serializers.ModelSerializer):
class Meta:
model = Model1
fields = "__all__"
class SerialModel2(serializers.ModelSerializer):
class Meta:
model = Model2
fields = "__all__"
So as shown even when the models have the same fields I need to use to different model serializers.
Can I have just one model serializer for both Model1 and Model2 ? If yes, please suggest me the way to do it.
You can create a generic BaseModelSerializer
(Django REST Framework doc) for this:
class BaseModelSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
and then use this as base class for the serializers of the concrete models:
class SerialModel1(BaseModelSerializer):
class Meta:
model = Model1
class SerialModel2(BaseModelSerializer):
class Meta:
model = Model2
This will inherit the fields specification, and override the model, so effectively configuring a serializer for the respective model, but reusing the field specification.
You can of course extend the BaseModelSerializer
with extra fields, or override fields if necessary.
Note that normally a ModelSerializer
is in fact already a "generic" serializer, in the sense that it can serialize any model you specify in the Meta
class. So in a way, using a BaseModelSerializer
is "overengineering" a bit, but it can prevent repeating code.