ContentTyep组件:
帮助我们关联所有数据库的表
帮助我们反向查询关联数据表中的所有策略信息
GenericForeignkey(帮助我们快速插入数据)
GenericRelation(用于反向查找)
有上面两个外键的字段仅用于快速查找,不再数据库生成表结构

一  需求

1.1需求信息

项目,有课程,学位课(不同的课程字段不一样),价格策略

问题,1 如何设计表结构,来表示这种规则
        2 为专题课,添加三个价格策略
          3 查询所有价格策略,并且显示对应的课程名称
          4 通过课程id,获取课程信息和价格策略

二  使用ContentType实现需求

2.1通过django提供的ContentType表构建

2.2models层创建

from django.db import models

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class Course(models.Model):
title = models.CharField(max_length=32)
# 不会在数据库中生成字段,只用于数据库操作
# policy = GenericRelation('PricePolicy',object_id_field='object_id',content_type_field='contentType') class DegreeCourse(models.Model):
title = models.CharField(max_length=32) 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()

2.3views层

from app01 import models
def 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 HttpResponse('创建成功')

最新文章

  1. [LeetCode] Rotate Image 旋转图像
  2. Web自动化测试 Selenium 3/3 https的配置
  3. Linux学习笔记(2)Linux学习注意事项
  4. Ubuntu下无法安装sun-java6-jdk的解决办法
  5. 如何使用mybatis《一》
  6. iOS - Swift NSEnumerator 迭代器
  7. Android开发之onClick事件的三种写法(转)
  8. [HTML5] Emmet
  9. [linux]磁盘挂载
  10. C#制作简易屏保(转)
  11. poj3429(有错)
  12. Java AOP - Aspectj
  13. Bootstrap入门(八)组件2:下拉菜单
  14. java 对时间(Date)随笔!
  15. 这一次带你彻底了解Cookie
  16. VS2017 WinFrom打包设置与教程
  17. 手动(原生ajax)和自动发送ajax请求 伪ajax(Ifrname)
  18. Java基础巩固——《Java核心技术基础·卷一:基础知识》
  19. Spring的quartz定时器重复执行二次的问题解决
  20. GUI相应鼠标事件

热门文章

  1. android圆形图像
  2. Unix系统编程()发送信号kill
  3. 8天学通MongoDB(mark)
  4. 32Mybatis_mybatis逆向工程自动生成代码
  5. MyBatis-Spring 使用总结
  6. 通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术
  7. 【BZOJ】1613: [Usaco2007 Jan]Running贝茜的晨练计划(dp)
  8. xdebug常用配置
  9. vue2.0非父子间进行通讯
  10. LAMP集群项目五 项目备份