一、引出问题

假如有这两张表,它们中的课程可能价格不一样、周期不一样、等等...不一样...,现在有一张价格策略表,怎么就用一张表报保存它们之间不同的数据呢?
可能你会这样:

确实是行!但是,如果有很多不同类型的课程,那么这样表就太多空值了!
没办法,这一张表不行,再创建一张不就行了,就像这样:

确实,对于这种情况,Django就是这样做的。
现在,有了 ContentType,我们只需创建三张表,就实现跟上面的效果一模一样了。
这是因为 Django 本身就会新建 django_content_type 这张表,这张表就保存了 model 中的表名。

二、ContentType
那么怎么创建这种关系呢?如下:

这里,DegreeCourse 表没有使用 GenericRelation,则不能使用下面说的第3点,否则报错,要想使用就跟 Course 表一样添加即可。
对于 GenericRelation 和 GenericForeignKey 类型字段,不会在数据库生成列!
三、测试
- # views.py
- from django.shortcuts import HttpResponse
- from django.contrib.contenttypes.models import ContentType
- from appxx import models
1、在价格策略表中添加一条数据。
- # 方式1
- def test(request):
- models.PricePolicy.objects.create(
- price=100,
- valid_period=7,
- object_id=3,
- content_type=ContentType.objects.get(model="course")
- )
- return HttpResponse("ok")
- # 方式2
- def test(request):
- models.PricePolicy.objects.create(
- price=200,
- valid_period=14,
- content_object=models.Course.objects.get(id=3) # 对应Course表id为3的价格策略
- # content_object=models.DegreeCourse.objects.get(id=2) # 对应DegreeCourse表id为2的价格策略
- )
- return HttpResponse("ok")
2、 根据某个价格策略对象,找到对应的表和数据。(是根据 GenericForeignKey类型字段实现的)
- def test(request):
- obj = models.PricePolicy.objects.get(id=1)
- print(obj.content_object.id, obj.content_object.name) # 自动找到
- return HttpResponse("ok")
3、 找到某个课程关联的所有价格策略。(是根据 GenericRelation 类型字段实现的)
- def test(request):
- obj = models.Course.objects.get(id=1)
- for item in obj.policy_list.all():
- print(item.id, item.price, item.valid_period)
- return HttpResponse("ok")
关系图:

四、总结
什么时候才用ContentType?
当一张表跟 n 张表动态地创建 ForeignKey 关系时,而不是创建太多列,因为数据表中会有很多空值。
ContentType 通过仅两列字段就实现了 n 张表的 ForeignKey 关系。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。