class MyRelatedModelSerialzier(serializers.ModelSerializer):
related_models_instance = MyModelSerializer(MyRelatedModel)
class Meta:
model = MyRelatedModel
fields = ['id', 'name', 'related_model_instance']
class MyModelSerailzier(serializer.ModelSerializer):
parent_id = serializer.SerializerMethodfield('get_parent_id')
def __init__(self, ParentModel):
self.parent = ParentModel
def get_parent_id():
# How to get the id of the object which is being serialized?
# In order to make some calculations
return self.parent
class Meta:
model = MyModel
fields = ['id', 'name', 'parent_id',....
这将在序列化过程中用父模型类初始化您的子模型