django:从该模型的实例获取模型的最佳实践方法 [英] django: best practice way to get model from an instance of that model
问题描述
说 my_instance
是模型 MyModel
。
我正在寻找一个好的
Say my_instance
is of model MyModel
.
I'm looking for a good way to do:
my_model = get_model_for_instance(my_instance)
我还没有发现任何真正直接的方法。
到目前为止,我想出了这样的方法:
I have not found any really direct way to do this. So far I have come up with this:
from django.db.models import get_model
my_model = get_model(my_instance._meta.app_label, my_instance.__class__.__name__)
这是可以接受吗?
还有 _meta.object_name
似乎和<$具有相同的效果吗? c $ c> __ class __.__ name __ 。可以?是好是坏?如果是,为什么?
Is this acceptable? Is it even a sure-fire, best practice way to do it?
There is also _meta.object_name
which seems to deliver the same as __class__.__name__
. Does it? Is better or worse? If so, why?
另外,如果应用标签在项目范围内多次出现,我怎么知道我得到了正确的模型?
这样的情况会使 get_model
不可靠吗?
Also, how do I know I'm getting the correct model if the app label occurs multiple times within the scope of the project, e.g. 'auth' from 'django.contrib.auth' and let there also be 'myproject.auth'?
Would such a case make get_model
unreliable?
感谢任何提示/指针和经验分享!
Thanks for any hints/pointers and sharing of experience!
推荐答案
my_model = type(my_instance)
要证明这一点,您可以创建另一个实例:
To prove it, you can create another instance:
my_new_instance = type(my_instance)()
这就是为什么没有直接方法的原因,因为python对象已经具有此功能。
This is why there's no direct way of doing it, because python objects already have this feature.
已更新...
我喜欢 marcinn的回复使用 type(x)
。这与原始答案( x .__ class __
)相同,但是与使用魔术属性相比,我更喜欢使用函数。以这种方式,我更喜欢使用 vars(x)
代替 x .__ dict __
, len( x)
到 x .__ len __
等等。
I liked marcinn's response that uses type(x)
. This is identical to what the original answer used (x.__class__
), but I prefer using functions over accessing magic attribtues. In this manner, I prefer using vars(x)
to x.__dict__
, len(x)
to x.__len__
and so on.
已更新2 ...
对于延迟实例(在评论中由@Cerin提及),您可以通过 instance._meta访问原始类。 proxy_for_model
。
For deferred instances (mentioned by @Cerin in comments) you can access the original class via instance._meta.proxy_for_model
.
这篇关于django:从该模型的实例获取模型的最佳实践方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!