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

  • 相关阅读:
    java中用spring实现数组类型输出
    #科委外文文献发现系统——导出word模板1.0
    #科委外文文献发现系统——项目管理
    终审项目展示
    M2事后会议报告
    【Beta版本发布】爬虫队长装备全面更新!
    Beta版本测试报告
    Beta阶段爬取数目预估
    团队作业Week14——源代码管理
    Daily Scrum NO.10
  • 原文地址:https://www.cnblogs.com/zhangqing979797/p/10105157.html
Copyright © 2011-2022 走看看