django rest 框架抽象类序列化器 [英] django rest framework abstract class serializer
问题描述
我有一些这样的模型:
class TypeBase(models.Model):
name = models.CharField(max_length=20)
class Meta:
abstract=True
class PersonType(TypeBase):
pass
class CompanyType(TypeBase):
pass
有了这个,我只想创建一个序列化器来保存所有这些字段类型(序列化、反序列化、更新和保存).
Having this, I want to create just one serializer that holds all these field types (serialization, deserialization, update and save).
更具体地说,我只需要一个序列化程序 (TypeBaseSerializer) 来在 UI 上打印下拉列表、序列化 json 响应、在发布时将其反序列化并将其保存为所有基于我的类型.
To be more specific, I want only one serializer (TypeBaseSerializer) that print the Dropdown on the UI, serialize the json response, deserialize it on post and save it for all my based types.
像这样:
class TypeBaseSerializer(serializers.Serializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
有可能吗?
推荐答案
我觉得下面的方法更简洁.您可以将基本序列化程序的抽象"字段设置为 true,并为所有子序列化程序添加通用逻辑.
I think the following approach is more cleaner. You can set "abstract" field to true for the base serializer and add your common logic for all child serializers.
class TypeBaseSerializer(serializers.ModelSerializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
abstract = True
def func(...):
# ... some logic
然后创建子序列化器并将它们用于数据操作.
And then create child serializers and use them for data manipulation.
class PersonTypeSerializer(TypeBaseSerializer):
class Meta:
model = PersonType
fields = ('id', 'name')
class CompanyTypeSerializer(TypeBaseSerializer):
class Meta:
model = CompanyType
fields = ('id', 'name')
现在您可以对每个模型正常使用这两个序列化程序.
Now you can use the both of these serializers normally for every model.
但是如果你真的想为两个模型都拥有一个序列化器,那么也为他创建一个容器模型和一个序列化器.那更干净:)
But if you really want to have one serializers for both the models, then create a container model and a serializer for him too. That is much cleaner :)
这篇关于django rest 框架抽象类序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!