我想实现一个Django Rest Framework视图,该视图返回模型实例对象的依赖关系树。这是该视图的代码:
class RoomTypeDependencies(viewsets.ViewSet):
def list(self, request, pk):
room_type = models.RoomType.objects.get(pk=pk)
dependency_tree = self.get_object_dependencies(room_type)
return Response(dependency_tree)
def get_object_dependencies(self, instance):
fields = instance.__class__._meta.get_fields()
dependencies_to_return = []
for field in fields:
print(field.name)
if field.__class__.__name__ == 'ManyToOneRel':
dependency_to_return = []
dependent_instances = getattr(instance, field.name)
for dependent_instance in dependent_instances:
dependency_to_return.append(self.get_object_dependencies(dependent_instance))
dependencies_to_return.append({field.__class__.__name__: dependency_to_return})
return Response({str(instance): dependencies_to_return})
一切似乎都能正常工作,但我希望getattr(instance, field.name)
返回与反向关系相对应的从属实例,就像使用model_object_instance.reverse_relationshio_name
模式一样,但是它返回一个 RelatedManager 对象代替。就我而言,问题在于我在字符串变量(field.name
)中具有反向关系名称。