【问题标题】:Best way of checking whether a certain Model instance is in fact an instance of a certain Model检查某个模型实例是否实际上是某个模型的实例的最佳方法
【发布时间】: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


    【解决方案1】:

    来自isinstancedocumentation

    如果 object 参数是 classinfo 的实例,则返回 True 论点,或其(直接、间接或虚拟)子类。如果 object 不是给定类型的对象,函数总是返回 错误的。如果 classinfo 是类型对象的元组(或递归,其他 这样的元组),如果 object 是任何 类型。如果 classinfo 不是类型或类型的元组和此类元组,则 引发 TypeError 异常。

    这意味着如果您的模型是另一个模型的子类,那么它们都将被标记为超类的实例

    例如:

    class A(object):
      pass
    
    class B(A):
      pass
    
    a = A()
    b = B() 
    
    print(isinstance(b,A))
    # True
    print(type(b)==type(A())
    # False
    

    总之你应该使用type(),因为在Django中有多种使用model inheritance的方法可能会产生错误的类型类结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2013-10-02
      • 2018-10-21
      • 2013-01-12
      • 2014-05-19
      • 2010-11-06
      相关资源
      最近更新 更多