django 之 ContentType的使用

时间:2023-03-10 01:17:03
django 之 ContentType的使用

1. ContentType 是干什么用的呢:

1. ContentType: 主要的作用就是Django orm的创建表的时候,可以方便多表查询使用,简化多表查询的过程

2.ContentType 最主要的是有一个表内有多个字段映射不同的表的时候可以使用了
#最主要的其实就是一个数据表会经常变化,这样的话使用ContentType 组件,这样方便后期的修改和处理

2. ContentType的案例简单分析:

from django.db import models

# Create your models here.

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
###加载ContentType 需要的模块组件 class Course(models.Model): #创建一个course 课程的表,免费的
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32) #它自己的字段 # 不会在数据库中生成字段,只用于数据库操作
policy = GenericRelation(to='PricePolicy') class DegreeCourse(models.Model): #创建一个收费的课程表
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
# 它自己的字段
policy = GenericRelation(to='PricePolicy') class PricePolicy(models.Model): #对应2个课程表的价格和学习的周期时间
id=models.AutoField(primary_key=True)
period=models.IntegerField()
price=models.DecimalField(max_digits=8,decimal_places=2) object_id=models.IntegerField() #这个就是精髓 这里的变量取值为object_id #不要加引号,因为文件里已经加载好了,不需要to=ContentType 加引号
content_type=models.ForeignKey(to=ContentType,null=True) #这个就是精髓 这里的变量取值为content_type # 引入一个字段,不会在数据库中创建,只用来做数据库操作
# content_obj = GenericForeignKey('content_type','object_id')
content_obj = GenericForeignKey() #以为上面2个变量赋值很巧妙, 所以这里GenericForeignKey()内不需要写内容了
使用一(给课程添加价格策略): 使用方法:
-给免费课django添加价格策略
course = models.Course.objects.get(pk=1)
ret = models.PricePolicy.objects.create(period=30, price=199.9, content_obj=course)
-给学位课程(python全栈开发)添加价格策略
degree_course = models.DegreeCourse.objects.get(pk=1)
ret = models.PricePolicy.objects.create(period=30, price=199.9, content_obj=degree_course)

使用一: 给课程添加价格策略

使用二:查询价格策略对应的课程:
price_policy = models.PricePolicy.objects.get(pk=1)
print(price_policy.content_obj)
使用三:通过课程获取价格策略
course = models.Course.objects.get(pk=1)
policy_list = couse.policy.all()

用contentType实现查询

# 查询所有价格策略,并且显示对应的课程名称
price_policy_list=models.PricePolicy.objects.all() #获取价格表的对象组
for price_policy in price_policy_list: #for 循环从列表组取出一个一个对象 print(price_policy.content_obj.name) #直接content_obj 可以多个表查询到想要的结果 # 查询django课程信息的所有价格策略
course=models.Course.objects.get(pk=1)
#policy_list 就是django这门课所有的价格策略对象
policy_list=course.policy.all()
for policy in policy_list:
print(policy.price) #查询python全栈开发的所有价格策略
degree_course=models.DegreeCourse.objects.get(pk=1)
policy_list=degree_course.policy.all()
for policy in policy_list:
print(policy.price)

使用contentType简单实现查询想要东西的代码