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

  • 相关阅读:
    记RestTemplate远程请求接口数据的一些注意事项
    记使用SpringDataMongonDb时,dao方法命名的一个已解决但不知道为什么的bug
    charles 打断点后传参或返回数据更改
    在liunx上搭建git仓库1
    jsonpath 提取参数
    pytest 参数化的使用1
    pytest中断言失败后,也可以继续执行其他用例
    charles开启弱网功能
    httprunner 参数化
    httprunner中debugtalk使用
  • 原文地址:https://www.cnblogs.com/zhangqing979797/p/10105157.html
Copyright © 2011-2022 走看看