我具有这样的数据库结构:
common_org:
id,
code,
title
special_org:
id,
code,
address
好的。为此,我创建了模型:
class CommonOrg(models.Model):
code = models.CharField()
title = models.CharField()
class SpecialOrg(models.Model):
code = models.CharField(null=True)
address= models.CharField()
现在,我想照常输出SpecialOrg,但是如果我有CommonOrg.code == SpecialOrg.code
,则将CommonOrg附加到SpecialOrg上,像这样:
{
"id": 1,
"code": "XYZ",
"address": "ADDRESS",
"common_org": {
"id": 2,
"code": "XYZ",
"title": "TITLE"
}
}
现在我可以使用serializers.RelatedField:
class CommonOrgField(serializers.RelatedField):
def to_representation(self, value):
class _CommonOrgSerializer(serializers.ModelSerializer):
class Meta:
model = CommonOrg
fields = '__all__'
representation = None
try:
common_org = CommonOrg.objects.get(code=value)
representation = _CommonOrgSerializer(common_org).data
except CommonOrg.DoesNotExist:
pass
return representation
class SpecialOrgSerializer(serializers.ModelSerializer):
class Meta:
model = SpecialOrg
fields = '__all__'
common_org = CommonOrgField(read_only=True, source='code')
但这对我来说很难看。
所以问题是:在DRF中实现它的正确方法是什么?数据库不是我的,我无法更改它。
答案 0 :(得分:1)
在大多数情况下,我要向序列化器添加一个只读字段,当该字段在数据库级别与当前模型不相关时,我将使用序列化器方法字段。您可以在这种情况下使用以下序列化器方法字段:
class SpecialOrgSerializer(serializers.ModelSerializer):
common_org = serializers.SerializerMethodField()
class Meta:
model = SpecialOrg
fields = '__all__'
def get_common_org(self, obj):
try:
common_org = CommonOrg.objects.get(code=value)
except CommonOrg.DoesNotExist:
return None
return _CommonOrgSerializer(common_org).data