zoukankan      html  css  js  c++  java
  • python之路_django之contenttype介绍

    表结构如下:

    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()
  • 相关阅读:
    完全卸载 Oracle
    Windows 下 Oracle 10g 手工创建数据库
    zip & unzip 命令
    J2EE的13种核心技术规范
    Windows 8发行预览版序列号
    wget百度百科
    Application's Life Cycle
    当前网络存在的安全问题
    Ubuntu 11.10 更换 LightDM 开机登录画面
    tmp文件夹的默认权限
  • 原文地址:https://www.cnblogs.com/seven-007/p/8483184.html
Copyright © 2011-2022 走看看