表结构如下:
class DegreeCourse(models.Model): """学位课程""" name = models.CharField(max_length=128, unique=True) # 忽略,用于GenericForeignKey反向查询,不会生成表字段,切勿删除 degreecourse_price_policy = GenericRelation("PricePolicy") def __str__(self): return self.name class Course(models.Model): """课程""" name = models.CharField(max_length=128, unique=True) # 用于GenericForeignKey反向查询,不会生成表字段,切勿删除 price_policy = GenericRelation("PricePolicy") class PricePolicy(models.Model): """价格与有课程效期表""" content_type = models.ForeignKey(ContentType) #ContentType为django提供的包含app名称和表名字段的表 object_id = models.PositiveIntegerField() #某表中一条信息的对应id content_object = GenericForeignKey('content_type', 'object_id') price = models.FloatField()
表操作介绍:
# 添加方式一 obj1 = models.DegreeCourse.objects.get(id=1) models.PricePolicy.objects.create(content_object=obj1,price=10) # 添加方式二 id = ContentType.objects.get(app_name='app01',modelname="degreecourse").id models.PricePolicy.objects.create(content_type_id=id,object_id=1, price=10) # 正向查找 price_list = models.PricePolicy.objects.all() for item in price_list: item.content_object # 反向查找 clist = models.DegreeCourse.objects.all() for item in clist: item.degreecourse_price_policy.all()