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

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

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

  1. # Application definition
  2.  
  3. INSTALLED_APPS = [
  4. \'django.contrib.admin\',
  5. \'django.contrib.auth\',
  6. \'django.contrib.contenttypes\',
  7. \'django.contrib.sessions\',
  8. \'django.contrib.messages\',
  9. \'django.contrib.staticfiles\',
  10. \'app01.apps.App01Config\',
  11. ]

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

  导入contenttypes组件:

  1. from django.contrib.contenttypes.models import ContentType

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

  1. class ContentType(models.Model):
  2. app_label = models.CharField(max_length=100)
  3. model = models.CharField(_(\'python model class name\'), max_length=100)
  4. objects = ContentTypeManager()
  5.  
  6. class Meta:
  7. verbose_name = _(\'content type\')
  8. verbose_name_plural = _(\'content types\')
  9. db_table = \'django_content_type\'
  10. unique_together = ((\'app_label\', \'model\'),)
  11.  
  12. def __str__(self):
  13. return self.name

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

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

  

  django_content_type记录了当前的Django项目中所有model所属的app(即app_label属性)以及model的名字(即model属性)。 

  django_content_type并不只是记录属性这么简单.了contenttypes是对model的一次封装,因此可以通过contenttypes动态的访问model类型,而不需要每次import具体的model类型。

  • ContentType.model_class() 

    获取当前ContentType类型所代表的模型类

  • ContentType.get_object_for_this_type() 

    使用当前ContentType类型所代表的模型类做一次get查询

  • ContentType.objects.get_for_id()
    • 通过id寻找ContentType类型,这个跟传统的get方法的区别就是它跟get_for_model共享一个缓存,因此更为推荐。
  • ContentType.objects.get_for_model()
    • 通过model或者model的实例来寻找ContentType类型

  假设我们创建如下模型,里面包含学位课程、专题课程、价格策略。

  价格策略既可以是专题课程的价格策略,也可以是学位课程的价格策略。需要在pricepolicy对象里添加非常多的ForeignKey。示例如下所示:

  1. class Food(models.Model):
  2. """
  3. id title
  4. 1 面包
  5. 2 牛奶
  6. """
  7. title = models.CharField(max_length=32)
  8. # 不会生成字段 只用于反向查询
  9. coupons = GenericRelation(to="Coupon")
  10. class Fruit(models.Model):
  11. """
  12. id title
  13. 1 苹果
  14. 2 香蕉
  15. """
  16. title = models.CharField(max_length=32)
  17. # 如果有40张表,则每一个都要建立外键关系
  18. class Coupon(models.Model):
  19. """
  20. id title food_id fruit_id
  21. 1 面包九五折 1 null
  22. 2 香蕉满10元减5元 null 2
  23. """
  24. title = models.CharField(max_length=32)
  25. food = models.ForeignKey(to="Food")
  26. fruit = models.ForeignKey(to="Fruit")

 

  这样做很傻,会造成代码重复和字段浪费。有一种优化的方案是:用两个字段去定位对象不用去创建多个外键关系

  1. # 方法二:用两个字段去定位对象不用去创建多个外键关系
  2. class Coupon(models.Model):
  3. """
  4. id title table_id object_id(对应表对应对象的ID)
  5. 1 面包九五折 1 1
  6. 2 香蕉满10元减5元 2 2
  7. """
  8. title = models.CharField(max_length=32)
  9. table = models.ForeignKey(to="Table") # 与table表建立外键关系
  10. object_id = models.IntegerField() # 由object_id定位到表中的某一个对象,但没有建立外键关系
  11.  
  12.  
  13. class Table(models.Model):
  14. """
  15. id app_name table_name
  16. 1 demo food
  17. 2 demo fruit
  18. """
  19. app_name = models.CharField(max_length=32)
  20. table_name = models.CharField(max_length=32)

  最好的方式是,只有当你需要对某个对象或模型进行评论时,才创建pricepolicy与那个模型的关系。示例如下所示:

  1. # 方法三:基于ContentTypes创建表结构
  2. class Coupon(models.Model):
  3. title = models.CharField(max_length=32) # 优惠券名称
  4. # 第一步:与ContentType表绑定外键关系
  5. content_type = models.ForeignKey(to=ContentType, on_delete=None)
  6. # 第二步:建立对象id
  7. object_id = models.IntegerField()
  8. # 第三步:content_type和object_id绑定外键关系
  9. content_object = GenericForeignKey("content_type", "object_id")

  学位课程、专题课程、价格策略基于django contenttypes创建表结构如下所示:

  1. from django.db import models
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  4.  
  5.  
  6. class DegreeCourse(models.Model):
  7. """学位课程"""
  8. name = models.CharField(max_length=128, unique=True)
  9. course_img = models.CharField(max_length=255, verbose_name="缩略图")
  10. brief = models.TextField(verbose_name="学位课程简介", )
  11.  
  12.  
  13. class Course(models.Model):
  14. """专题课程"""
  15. name = models.CharField(max_length=128, unique=True)
  16. course_img = models.CharField(max_length=255)
  17.  
  18. # 不会在数据库生成列,只用于帮助你进行查询
  19. policy_list = GenericRelation("PricePolicy")
  20.  
  21.  
  22. class PricePolicy(models.Model):
  23. """价格策略表"""
  24. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # 关联course or degree_course
  25. object_id = models.PositiveIntegerField() # 正整数PositiveInteger
  26.  
  27. # GenericForeignKey不会在数据库生成列,只用于帮助你进行添加和查询
  28. content_object = GenericForeignKey(\'content_type\', \'object_id\') # 将两个字段放在这个对象中
  29.  
  30. # 周期
  31. valid_period_choices = (
  32. (1, \'1\'),
  33. (3, \'3\'),
  34. (7, \'1\'), (14, \'2\'),
  35. (30, \'1个月\'),
  36. (60, \'2个月\'),
  37. (90, \'3个月\'),
  38. (180, \'6个月\'), (210, \'12个月\'),
  39. (540, \'18个月\'), (720, \'24个月\'),
  40. )
  41. # 价格
  42. valid_period = models.SmallIntegerField(choices=valid_period_choices)
  43. price = models.FloatField()

  Django ContentType提供了一种GenericForeignKey的类型,通过这种类型可以指定content_object。

  GenericForeignKey不会在数据库生成列,只用于帮助你进行添加查询

  GenericRelation不会在数据库生成列,只用于帮助你进行查询

  • content_type: 内容类型,代表了模型的名字(比如Course,DegreeCourse)

  • object_id: 传入对象的id

  • content_object: 传入的实例化对象,其包含两个属性content_type和object_id。

  1. from django.shortcuts import render, HttpResponse
  2. from app01 import models
  3. from django.contrib.contenttypes.models import ContentType
  4.  
  5. def test(request):
      # 方法一:
  6. models.PricePolicy.objects.create(
  7. valid_period=7,
  8. price=6.6,
  9. content_type=ContentType.objects.get(model="course"),
  10. object_id=1
  11. )
  12.   # 方法二:
  13. models.PricePolicy.objects.create(
  14. valid_period=14,
  15. price=9.9,
  16. content_object=models.Course.objects.get(id=1) # \'content_type\', \'object_id\'
  17. )
  18. return HttpResponse("...")

  访问http://127.0.0.1:8000/test/ 后,查看价格策略表保存的数据:

  

  这里以查看管理课程名称为例:

  1. from django.shortcuts import render, HttpResponse
  2. from app01 import models
  3. from django.contrib.contenttypes.models import ContentType
  4.  
  5. def test(request):
  6. price = models.PricePolicy.objects.get(id=2)
  7. print(price.content_object.name) # 21天入门python 即自动帮忙找到对应的对象
  8.  
  9. return HttpResponse("...")

  注意这里需要利用到GenericRelation。

  1. from django.shortcuts import render, HttpResponse
  2. from app01 import models
  3. from django.contrib.contenttypes.models import ContentType
  4.  
  5. def test(request):
  6. obj = models.Course.objects.get(id=1)
  7. print(obj.policy_list.all()) # <QuerySet [<PricePolicy: PricePolicy object (1)>, <PricePolicy: PricePolicy object (2)>]>
  8.  
  9. return HttpResponse("...")

  查询结果是一个QuerySet对象,如果想让查询结果更加清楚:

  1. from django.shortcuts import render, HttpResponse
  2. from app01 import models
  3. from django.contrib.contenttypes.models import ContentType
  4.  
  5. def test(request):
  6.  
  7. obj = models.Course.objects.get(id=1)
  8. for item in obj.policy_list.all():
  9. print(item.id, item.valid_period, item.price)
  10. """
  11. 1 7 6.6
  12. 2 14 9.9
  13. """
  14. return HttpResponse("...")

  如果一张表与N张表动态地要创建Foreign Key关系,如果创建 Foreign key 将生成很多列,这样很多都是空的,造成严重浪费空间。只要是一张表要和多张表建立外键关系的情况,都可以考虑使用django的ContentType组件来帮助实现,以简化表结构的设计。

  ContentType组件的作用:可以通过两个字段(GenericForeignKey, GenericRelation),在保证列数不变的情况下,让一张表和N张表做Foreign Key关系。

 

版权声明:本文为xiugeng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xiugeng/p/9831665.html