django内置组件——contenttypes

一、什么是Django ContentTypes?

  Django ContentTypes是由Django框架提供的一个核心功能,它对当前项目中所有基于Django驱动的model提供了更高层次的抽象接口。主要用来创建模型间的通用关系(generic relation)。

  进一步了解ContentTypes可以直接查阅以下这两个链接:

二、Django ContentTypes做了什么?

  当创建一个django项目时,可以看到在默认的INSTALL_APPS已经包含了django.contrib.contenttypes。

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

  注意:django.contrib.contenttypes是在django.contrib.auth之后,这是因为auth中的permission系统是根据contenttypes来实现的

  导入contenttypes组件:

from django.contrib.contenttypes.models import ContentType

  查看django.contrib.contenttypes.models.ContentType类的内容:

class ContentType(models.Model):
    app_label = models.CharField(max_length=100)
    model = models.CharField(_('python model class name'), max_length=100)
    objects = ContentTypeManager()

    class Meta:
        verbose_name = _('content type')
        verbose_name_plural = _('content types')
        db_table = 'django_content_type'
        unique_together = (('app_label', 'model'),)

    def __str__(self):
        return self.name

  可以看到ContentType就是一个简单的django model,而且它在数据库中的表的名字为django_content_type。 

  在第一次对Django的model进行migrate之后,就可以发现在数据库中出现了一张默认生成的名为django_content_type的表。 
如果没有建立任何的model,默认django_content_type是前六项:

  

猜你喜欢

转载自www.cnblogs.com/xiugeng/p/9831665.html