• django的orm--contenttype操作


    1,在django操作orm生成表时,会自动生成一个包含所有表名称的表.

    名字就叫:

     2,实际操作.

    class PricePolicy(models.Model):
        """价格与有课程效期表"""
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type', 'object_id')
    
        valid_period_choices = ((1, '1天'), (3, '3天'),
                                (7, '1周'), (14, '2周'),
                                (30, '1个月'),
                                (60, '2个月'),
                                (90, '3个月'),
                                (180, '6个月'), (210, '12个月'),
                                (540, '18个月'), (720, '24个月'),
                                )
        valid_period = models.SmallIntegerField(choices=valid_period_choices)
        price = models.FloatField()
    
    
    
    class Course(models.Model):
        attachment_path = models.CharField(max_length=128,     
        verbose_name="课件路径", blank=True, null=True)
        status_choices = ((0, '上线'), (1, '下线'), (2, '预上线'))
        status = models.SmallIntegerField(choices=status_choices, 
        default=0)
        template_id = models.SmallIntegerField("前端模板id", 
        default=1)
        coupon = GenericRelation("Coupon")
        # 用于GenericForeignKey反向查询,不会生成表字段,切勿删除
        price_policy = GenericRelation("PricePolicy")
    model
    course_obj=models.Course.object.filter(id=1)
    price_list=course_obj.price_policy.all()  #获取与之关联的price_policy的所有对象
    
    for price in price_list:     #获取所有字段,和操作其他orm一样.
        print(price.valid_period)
        print(price.price)
    view

    上面是反向查询,下面是正向查询

    price_obj=models.PricePolicy.objects.filter(id=1)
    status=price_obj.content_type.status  
    #可以直接通过content_type查询course表中字段
  • 相关阅读:
    Centos7.0 安装Oralce 11g数据库
    python学习:基础数据类型
    Centos7.0 安装MySQL数据库
    Centos7.0 安装MariaDB数据库
    微服务的详情
    Class -- 10 -- Method类常用方法解析
    遍历list的三种方式
    使用@Autowired注解警告Field injection is not recommended
    java中的两种排序工具Arrays和Collections的使用
    java的reflection和introspector
  • 原文地址:https://www.cnblogs.com/52forjie/p/8491016.html
Copyright © 2020-2023  润新知