【发布时间】:2020-09-28 05:22:01
【问题描述】:
我正在尝试编写一个类,该类将我的应用程序中的模型实例作为其__init__ 中的参数。
在阅读该主题时,我偶然发现了这个问题:django: best practice way to get model from an instance of that model,它认为简单地使用type(instance) 是最好的方法。
尽管立即使用它可能很诱人,但使用isinstance(instance, model) 不是更好的解决方案吗?
比如说(来自我自己的代码):
from app_name.models import Model1, Model2, ... ModelN
MODELS = (Model1, Model2 ... ModelN)
然后在类本身(在我的例子中是 Graph)内部,执行如下操作:
class Graph():
model_instance = None
model = None
def __init__(self, model_instance):
if isinstance(model_instance, MODELS):
for a_model in MODELS:
if isinstance(model_instance, a_model):
self.model = a_model
self.model_instance = model_instance
...
作为一个初学者,我认为这是我能想到的最好方法,但我也认为有更顺畅/更好的方法可以做到这一点。可能是一种更“可读”的方式? 优点?缺点?
感谢所有对此的反馈!谢谢!
那些对这个问题的整个上下文感兴趣的人,请查看我在 GitHub 上的项目:https://github.com/VBoB13/TeachAdmin 您可以在此处找到带有上述代码的文件:https://github.com/VBoB13/TeachAdmin/blob/master/teachadmin/graph.py
【问题讨论】:
标签: python python-3.x django django-models