1.models
class PricePolicy(models.Model): """价格与有课程效期表""" content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') valid_period_choices = ((1, '1天'), (3, '3天'), (7, '1周'), (14, '2周'), (30, '1个月'), (60, '2个月'), (90, '3个月'), (180, '6个月'), (210, '12个月'), (540, '18个月'), (720, '24个月'), ) valid_period = models.SmallIntegerField(choices=valid_period_choices) price = models.FloatField() class Meta: unique_together = ("content_type", 'object_id', "valid_period") def __str__(self): return "%s(%s)%s" % (self.content_object, self.get_valid_period_display(), self.price) class Meta: verbose_name = "价格与有课程效期表" verbose_name_plural = "价格与有课程效期表" class DegreeCourse(models.Model): """学位课程""" name = models.CharField(max_length=128, unique=True) course_img = models.CharField(max_length=255, verbose_name="缩略图") brief = models.TextField(verbose_name="学位课程简介", ) total_scholarship = models.PositiveIntegerField(verbose_name="总奖学金(贝里)", default=40000) mentor_compensation_bonus = models.PositiveIntegerField(verbose_name="本课程的导师辅导费用(贝里)", default=15000) # 忽略,用于GenericForeignKey反向查询, 不会生成表字段,切勿删除 coupon = GenericRelation("Coupon") # 为了计算学位奖学金 period = models.PositiveIntegerField(verbose_name="建议学习周期(days)", default=150) prerequisite = models.TextField(verbose_name="课程先修要求", max_length=1024) teachers = models.ManyToManyField("Teacher", verbose_name="课程讲师") # 忽略,用于GenericForeignKey反向查询,不会生成表字段,切勿删除 degreecourse_price_policy = GenericRelation("PricePolicy") def __str__(self): return self.name class Meta: verbose_name = "学位课程" ve rbose_name_plural = "学位课程"
2.views
正向查找:models对象.content_object得到的是models对象
反向查找:models对象.反向关联字段.all()得到的是QuerySet对象
添加:content_type+_id其他不变
from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def index(request): '''查看价格与有课程效期表''' DegreeCourse_obj=models.PricePolicy.objects.get(id=1).content_object '''通过content_object直接找到与其关联的models对象''' print('aaaaa',DegreeCourse_obj,type(DegreeCourse_obj)) '''反向关联查找''' b = models.DegreeCourse.objects.get(id=1).degreecourse_price_policy.all() print('bbbb',b) '''ADD''' models.PricePolicy.objects.create(content_type_id=1,object_id=1,valid_period=60,price=6666) return HttpResponse('ok!!!')