是否可以让 Python 中的类在类属性中相互引用?例如:
class A(object):
ref = B
class B(object):
reverse = A
具体用例是一个 Django 模型,它是 Django Rest Framework 的序列化程序。通常,您必须将 Django 模型实例传递给其序列化程序以实例化序列化程序,但我希望能够从模型实例中获取序列化程序,如下所示:
class MyModel(models.Model):
class Meta:
default_serializer = MySerializer
def get_default_serializer(self):
return self.Meta.default_serializer(self)
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
# This is how you normally get a serializer:
MySerializer(MyModel.objects.get(id=1))
# But I want to do this, so I don't need to know what the default
# serializer is in order to get one:
MyModel.objects.get(id=1).get_default_serializer()
我知道 Django 模型允许您使用字符串作为外键参数,然后它会延迟加载相关模型。我可以在这里实现类似的东西吗?