ContentType 组件,models.py文件里操作设置字段,ContentType表做关联以后连表查询

models.py文件里操作,设置字段

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation

# 免费课程
class Course(models.Model):
    ...
    policy = GenericRelation(to='PricePlice')

# 学位课
class DegreeCourse(models.Model):
    ...
    policy = GenericRelation(to='PricePlice')   # 后面添加一个policy字段,只是作为正向连表查询

# 价位策略表
class PricePlice(models.Model):
    ...
    # 当object_id跟很多表要做关联的时候,可以考虑ContentType组件,他能够快速帮我们查询,和插入数据
    object_id = models.IntegerField()    # 因为跟内置的GenericForeignKey类做关联,最好字段名object_id ,方便连表查询
    content_type = models.ForeignKey(to=ContentType, null=True)  # 添加价格类型字段,关联到内置的ContentType表上

    # GenericForeignKey 类会自动创建 object_id,content_type 这两个字段,也方便我们连表查询
    content_obj = GenericForeignKey(ct_field='content_type', fk_field='object_id')  # 只是作为连表反向查询,因为上面已经设定了字段名为object_id,content_type所以可以不用写参数

ContentType表做关联以后,连表查询

# 插入数据,content_obj 赋值给一个对象,相当于将 对象的id,对象的表名,赋值给了PricePlice表里的 object_id,content_type 两个字段
object_id = models.Course.objects.get(id=1)
models.PricePlice.objects.create(price=20000, content_obj=object_id) # 免费课程python这门课程添加了价格策略

degree_course = models.DegreeCourse.objects.get(id=1)
models.PricePlice.objects.create(price=10, content_obj=degree_course) # 给java学位课程添加了价格策略


# 正向查询,在models 的课程表 加入字段 policy = GenericRelation(to='PricePlice'),就可以直接通过policy字段连表查询价格策略表
degree_course = models.DegreeCourse.objects.filter(id=1).first()
price_plice = degree_course.policy.all().values("price", "object_id")  # 查询java 课程的价格策略,对象点policy,就是正向查询的对象
print(price_plice)

# 反向查询,在models 的PricePlice表里加入字段 content_obj = GenericForeignKey(ct_field='content_type', fk_field='object_id') ,就可以直接通过policy字段连表方向查询价格策略表
price_plices = models.PricePlice.objects.all()     # 以后直接连表查询用models里加的字段
for price_plice in price_plices:
    print(price_plice.content_obj.name, price_plice.price)   # 所有价格策略,并且显示对应的课程名称,,对象点content_obj,就是反响查询的对象
models.py文件里操作
posted @ 2019-04-15 11:56  星牧  阅读(148)  评论(0编辑  收藏  举报