1

I want to get a entity through a ReferencePropery in this way.

getattr(model, refrence)

where model is a db.Model and reference is db.ReferenceProperty. But I get a KindError, which I can avoid by adding import of following sort.

from foomodule import ReferedKind

Where ReferedKind is the class of the entity I want to get by above getattr.

But my problem is in my case because of the nature of the function I want to call this in, the model can belong to any Model class of mine. So I don't know what the ReferedKind will be.

How can I call getattr and get the referred entity without importing every possible model class?

Is there a way I can know the class of a entity referred by a ReferanceProperty in advance so I can dynamically import it?

Aditional info

I am writing a function that would return a json serializable python dict. Because in some cases dictionary returned by db.to_dict() is not json serializable. So the function doesn't know in advance what kind of a model it will have to put into a dict.

4

1 回答 1

1

通常,您需要在执行任何操作之前导入所有可以检索的潜在模型。

你为自己制造困难。

您这样做的唯一方法是在比 db.Model 或 ndb.Model 更低的级别上工作以获取原始数据然后对其进行检查,然后您仍然需要在取消引用引用属性或获取密钥之前导入模型。

如果您决定这样做 ndm 会更容易,因为它没有引用属性,而是 KeyProperty,您可以使用 getattr,检查您是否有密钥,然后获取引用为密钥的对象。

如果你想坚持使用 db. 它会很乱,因为你需要使用get_value_for_datastore

这将涉及,

获取实体的类,获取类的属性,然后调用 get_value_for_datastore 传入实例,然后假设您已导入,您可以获得密钥。

因此,如果您有来自数据存储区的名为 foo 的实例,您将

prop = getattr(foo.__class__,"the_property_name")
obj_key = prop.get_value_for_datastore(foo)

然后您需要从密钥中获取类型,然后在 get() 密钥之前确定如何导入该类型的模型,否则您仍然会得到KindError

我不确定所有的努力是否值得,你会发现只导入模型更容易。您最终需要在使用之前导入任何模型。您可能会获得的唯一一件事是延迟导入可能会节省一些启动时间。

于 2013-07-01T10:11:28.300 回答