标签:view span 文件 帮助 mode from 获取 ret 解决
如果 继续增加课程 价格策略表还得增加字段
这样django自带一个contentType 帮助我们解决表之间的依赖关系:
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class DegreeCourse(models.Model): """ 学位课表 """ name = models.CharField(max_length=32) class Course(models.Model): """ 课程表 """ name = models.CharField(max_length=32) # 数据库不生成,只用于链表查询 policy_list = GenericRelation("PricePolicy") class PricePolicy(models.Model): """ 策略表 """ content_type = models.ForeignKey(ContentType,verbose_name="关联的表名称") #存表名的id object_id = models.PositiveIntegerField(verbose_name="关联表中数据行的id") # 不在数据库中生成,只用于帮助你做数据操作 content_object = GenericForeignKey(‘content_type‘, ‘object_id‘) period = models.CharField(max_length=32) price = models.FloatField()
views.py
def testtype(request): # 创建课程golang对应的三个价格列表 obj = Course.objects.filter(name="golang").first() # 获取课程对象 PricePolicy.objects.create(price=9.9,period=30,content_object=obj) # 通过contenttype创建 obj1 = Course.objects.filter(name="golang").first() PricePolicy.objects.create(price=19.9,period=60,content_object=obj1) obj2 = Course.objects.filter(name="golang").first() PricePolicy.objects.create(price=29.9,period=90,content_object=obj2) # 取golang课程对应的价格列表 objs = Course.objects.filter(name="golang").first() price_policys = objs.policy_list.all() print(price_policys) return HttpResponse("...")
PS:
for priceplicy in price_list: # 取出一个个的models对象 . content_obj 就可以去到相对应的 print(priceplicy.content_obj.name,priceplicy.price, priceplicy.period) course_obj = Course.objects.get(id=1) obj = course_obj.policy_list.filter(id=3) # 和正常一样取值 objs = course_obj.policy_list.all()
标签:view span 文件 帮助 mode from 获取 ret 解决
原文地址:https://www.cnblogs.com/liujiliang/p/10008888.html