是否可以在类属性中使用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模型允许你使用字符串作为外键参数,然后它延迟加载相关模型。我可以在这里实施类似的东西吗?