一:介绍
ContentType组件是Django中内置的组件,可以快速的帮助开发者进行联表设计
二:使用
models层:
from django.db import modelsfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.contenttypes.fields import GenericForeignKey, GenericRelationclass Course(models.Model): title = models.CharField(max_length=32) # 不会在数据库中生成字段,只用于数据库查询操作,结果为 多个PricePolicy对象 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表做外键关联 contentType = models.ForeignKey(to=ContentType) object_id = models.PositiveIntegerField() # 引入一个字段,不会在数据库中创建,只用来做数据库操作 # content_obj = GenericForeignKey('contentType', 'object_id') period = models.CharField(max_length=32) price = models.FloatField()
views:
from app01 import modelsdef 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')