zoukankan      html  css  js  c++  java
  • django model content_type 使用

    一.关于content_type 使用

    1.引入模块在models

    from django.db import models
    from django.contrib.contenttypes.models import ContentType #使用ContentType 
    from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation #正向查询, 反向查询

    2. 创建数据库,普通课程, 私人课程, 价格策略

    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)
        price_policy_list = GenericRelation("PricePolicy") #只是为了反向查询
    
    
    class DegreeCourse(models.Model):
        title = models.CharField(max_length=32)
        price_policy_list = GenericRelation("PricePolicy") #只是为了反向查询
    
    
    class PricePolicy(models.Model):
        """
        价格策略
        """
        price = models.IntegerField()
        period = models.IntegerField()
    
        content_type = models.ForeignKey(ContentType, verbose_name="关联的表名称",on_delete=models.CASCADE)
        object_id = models.IntegerField(verbose_name="关联表的数据行ID")
    
        content_object = GenericForeignKey("content_type", "object_id") #通过找到content_type 找到 关联的表名, object_id 找到行id

    最后创建数据库

    3.在test.views 增加,反向查询

    def test(request):
        obj = models.DegreeCourse.objects.filter(title="老人与海").first()#找到对象
        models.PricePolicy.objects.create(price=9.9, period=30, content_object=obj)# content_object=obj
        obj2 = models.DegreeCourse.objects.filter(title="老人与海").first()
        models.PricePolicy.objects.create(price=19.9, period=30, content_object=obj2)
        obj3 = models.DegreeCourse.objects.filter(title="老人与海").first()
        models.PricePolicy.objects.create(price=29.9, period=30, content_object=obj3)
    
        # 反向查询
        course = models.DegreeCourse.objects.filter(id=1).first()
    
        price_policys = course.price_policy_list.all()
        print(price_policys)
    
        return HttpResponse("OK")

    结果

    文章引用 https://www.cnblogs.com/c-x-m/articles/8991616.html#autoid-0-0-0

  • 相关阅读:
    Spark源码分析之Sort-Based Shuffle读写流程
    浅谈Spark2.x中的Structured Streaming
    Spark应用提交
    js面向对象插件的做法框架new goBuy('.cakeItem',{ add:'.add', reduce:'.reduce' },[1,0.7,0.6]);
    dubbo 运行过程
    linux 监控命令
    DUBBO Thread pool is EXHAUSTED!
    线程池深入(li)
    高性能、高流量Java Web站点打造的22条建议
    Maven 打胖jar
  • 原文地址:https://www.cnblogs.com/zhangqing979797/p/10105157.html
Copyright © 2011-2022 走看看