zoukankan      html  css  js  c++  java
  • django的contenttype表

    https://blog.csdn.net/aaronthon/article/details/81714496

    这篇文章已经非常详细了,供自己以后忘了...回看......

     总结:  

    当一张表和多个表FK关联,并且多个FK中只能选择其中一个或其中n个时,可以利用contenttype,固定用三个字段           

      

    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)  # 关联course or degree_course
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id') # obj.content_object获取关联对象
    

      

    price_policy = GenericRelation("PricePolicy")  # GenericForeignKey反向查询,不会生成表字段  obj.price_policy.all()获取所有关联对象

      

    实际用法

    from .models import PricePolicy
    p=PricePolicy.objects.get(pk=1)
    p.content_object
    <Course: 英语基础(付费)>
    
    from .models import Course
    c=Course.objects.get(pk=1)
    c.price_policy.all()
    <QuerySet [<PricePolicy: 英语基础(付费)(2周)100.0>, <PricePolicy: 英语基础(付费)(1个月)200.0>, <PricePolicy: 英语基础(付费)(2个月)300.0>]>
    

      

  • 相关阅读:
    Super Mario
    SPOJ Count on a tree
    SPOJ DQUERY
    51nod 区间中第K大的数
    POJ2104 K-th Number
    矩阵模板
    Sasha and Array
    MVC RenderSection
    Lazy Acquisition
    .net4.5 await async 简化之后的异步编程模型
  • 原文地址:https://www.cnblogs.com/amber-liu/p/10120723.html
Copyright © 2011-2022 走看看