zoukankan      html  css  js  c++  java
  • ContentType组件

    django提供的一个快速连表操作的组件

    适用于:一个字段确定不了唯一;
    
      如:pricepolicy表中,course_id和content_type中对应的课程类型id才能确定唯一;

    model.py中新建的类会自动在contenttype表新增字段;

    避免自己在建立中间表;

    使用,在models.py中:
    课程可能会有免费课,轻课,收费课等
    from
    django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation class Course(models.Model): name = models.CharField(max_length=32) # 不会在数据库生成数据,只是用来连表操作 price_police=GenericRelation(to='PricePolicy') class PricePolicy(models.Model): period = models.IntegerField() price = models.CharField(max_length=32) # 注意不能用外键关联 # course_id = models.IntegerField(null=True)

    #由于课程有多个,需要两个字段才能确定唯一,课程id不能用外键,因为对应多个。
         #命名必须用object_id 替代course_id,在调用GenericForeignKey时,就不用再传参数
    object_id = models.IntegerField(null=True) content_type = models.ForeignKey(to=ContentType,null=True) # 该字段不会在数据库生成字段,只是用来做连表操作 obj=GenericForeignKey()
    在view.py中使用:
        1 为django入门课,添加三个价格策略
            ret = models.PricePolicy.objects.create(period=60, price='99.9', obj=course)
        2 查询所有价格策略,并且显示对应的课程名称
            ret=models.PricePolicy.objects.all()
            for i in ret:
                print(i.price)
                print(i.obj.name)  #课程名称
        3 通过课程id,获取课程信息和价格策略
            course=models.Course.objects.get(pk=1)
            price_polices=course.price_police.all()
            for i in price_polices:
                print(i.price)
                print(i.period)
  • 相关阅读:
    myelipse与idea的javaweb项目创建
    入站规则和出站规则设置
    NAT技术基本原理与应用
    如何将sqlserver数据中的数据导出到服务器
    如何将SqlServer中表结构以及表数据全部导出
    国外服务器--新加坡服务器
    windows server2008 创建新用户 远程桌面连接 和 多用户登录问题
    程序员应该关注的国外IT网站
    IDEA创建普通java和web项目教程
    IIS Express 通过IP访问的方法和坑
  • 原文地址:https://www.cnblogs.com/xuechengeng/p/10454659.html
Copyright © 2011-2022 走看看