ContentType
帮助我们快速连表,可以跟多个表做关联。比如:
- 免费课程,收费课程,学位课程等跟价格策略关联。
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
class Course(models.Model):
title = models.CharField(max_length=32)
# 不会在数据库中生成字段,只用于数据库操作
policy = GenericRelation('PricePolicy',object_id_field='object_id',content_type_field='contentType')
class DegreeCourse(models.Model):
title = models.CharField(max_length=32)
policy = GenericRelation('PricePolicy',object_id_field='object_id',content_type_field='contentType')
class PricePolicy(models.Model):
# 跟ContentType表做外键关联,跟表id关联
contentType = models.ForeignKey(to=ContentType)
# 正数。通过表id和课程id可以唯一确定是哪个表的那个课程
object_id = models.PositiveIntegerField()
# 引入一个字段,不会在数据库中创建,只用来做数据库操作
content_obj = GenericForeignKey('contentType', 'object_id')
period = models.CharField(max_length=32)
price = models.FloatField()
view层
from app01 import models
def test(request):
import json
# 方式一插入价格规则
# ret=models.ContentType.objects.filter(model='course').first()
# course=models.Course.objects.filter(pk=1).first()
# print(ret.id)
# models.PricePolicy.objects.create(period='30',price=100,object_id=course.id,contentType_id=ret.id)
# 方式二插入价格规则
course=models.Course.objects.filter(pk=1).first()
content_obj=course #会自动的把课程id放到object_id上,并且去ContentType表中查询课程表的id,放到contentType上。
models.PricePolicy.objects.create(period='60',price=800,content_obj=course)
# 增加学位课,价格规则
degreecourse = models.DegreeCourse.objects.filter(pk=1).first()
models.PricePolicy.objects.create(period='60', price=800, content_obj=degreecourse)
# 查询所有价格策略,并且显示对应的课程名称
# ret=models.PricePolicy.objects.all()
# for i in ret:
# print(i.price)
# print(i.period)
# # content_obj 就是代指关联的课程,或者学位课程的那个对象
# print(type(i.content_obj))
# print(i.content_obj.title)
# 通过课程id,获取课程信息和价格策略
course=models.Course.objects.filter(pk=1).first()
print(course.policy.all())
return render(request,'test.html')