ContentType组件

django提供的一个快速连表操作的组件

适用于:一个字段确定不了唯一;

  如:pricepolicy表中,course_id和content_type中对应的课程类型id才能确定唯一;

model.py中新建的类会自动在contenttype表新增字段;

避免自己在建立中间表;

使用,在models.py中:
课程可能会有免费课,轻课,收费课等
from
django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation class Course(models.Model): name = models.CharField(max_length=32) # 不会在数据库生成数据,只是用来连表操作 price_police=GenericRelation(to='PricePolicy') class PricePolicy(models.Model): period = models.IntegerField() price = models.CharField(max_length=32) # 注意不能用外键关联 # course_id = models.IntegerField(null=True)

#由于课程有多个,需要两个字段才能确定唯一,课程id不能用外键,因为对应多个。
     #命名必须用object_id 替代course_id,在调用GenericForeignKey时,就不用再传参数
object_id = models.IntegerField(null=True) content_type = models.ForeignKey(to=ContentType,null=True) # 该字段不会在数据库生成字段,只是用来做连表操作 obj=GenericForeignKey()
在view.py中使用:
    1 为django入门课,添加三个价格策略
        ret = models.PricePolicy.objects.create(period=60, price='99.9', obj=course)
    2 查询所有价格策略,并且显示对应的课程名称
        ret=models.PricePolicy.objects.all()
        for i in ret:
            print(i.price)
            print(i.obj.name)  #课程名称
    3 通过课程id,获取课程信息和价格策略
        course=models.Course.objects.get(pk=1)
        price_polices=course.price_police.all()
        for i in price_polices:
            print(i.price)
            print(i.period)
原文地址:https://www.cnblogs.com/xuechengeng/p/10454659.html