• django组件之ContentType


    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('创建成功')
  • 相关阅读:
    一些性能查询的SQL 备忘
    Oracle Stream配置详细步骤
    Oracle 一次生产分库,升级,迁移
    Oracle数据文件和临时文件的管理
    db_recovery_file_dest_size 修改大一点及删除归档日志 |转|
    android启动优化
    C++ primer 中文第三版 阅读笔记 第八章
    XMPP通讯开发-好友获取界面设计
    用SHELL与列表处理了件尴尬事
    各种快递查询--Api接口
  • 原文地址:https://www.cnblogs.com/zhaijihai/p/10148522.html
Copyright © 2020-2023  润新知