Django 1.7 ContentType与应用

时间:2018-06-28 18:43:47

标签: python django django-models

我正在使用django 1.7,我想知道使用

的区别
ContentType.objects.get(app_label="app_name", model="model_name")

apps.get_model('app_name', 'model_name')

它们都从模型中获取相同的信息吗?使用apps.get_model有什么好处?

1 个答案:

答案 0 :(得分:0)

ContentType.objects.get(app_label="app_name", model="model_name")

仅是ContentType模型类的返回实例。但是

apps.get_model('app_name', 'model_name')

返回'app_name', 'model_name'中的model class

代码中的更多详细信息:

In [1]: from django.contrib.contenttypes.models import ContentType

In [2]: from django.apps import apps

In [3]: ct = ContentType.objects.get(app_label="myapp", model="bar")

In [4]: Bar = apps.get_model("myapp.bar")

In [5]: ct == Bar
Out[5]: False

In [6]: ct.model_class() == Bar
Out[6]: True

In [7]: Bar.objects.count()
Out[7]: 3

In [8]: ct.objects.count()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-c27dfd7c7cf5> in <module>()
----> 1 ct.objects.count()

/home/user/.virtualenvs/so/local/lib/python2.7/site-packages/django/db/models/manager.pyc in __get__(self, instance, cls)
    184     def __get__(self, instance, cls=None):
    185         if instance is not None:
--> 186             raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__)
    187 
    188         if cls._meta.abstract:

AttributeError: Manager isn't accessible via ContentType instances