zoukankan      html  css  js  c++  java
  • Django contenttype 组件

    第一步 我们先设计表

    有大课和小课 他们的价格各不相同

    第一次设计

     第二次设计

     第三次设计

     注:表记录那张表 由contenttype组件实现

    上面傻种都是可以 但是我们今天主要看的是第三种

    # content type 表不需要你自己生成 在你建表的时候 django会自动给你生成
    from
    django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation # Create your models here. class BigCourse(models.Model): """大课""" name = models.CharField(max_length=128) # 不会创建额外表,帮助你快速操作 price_policy = GenericRelation("PricePolicy") class SmallCourse(models.Model): """""" name = models.CharField(max_length=128) class PricePolicy(models.Model): """价格策略""" period = models.IntegerField(verbose_name='周期') price = models.FloatField(verbose_name='价格') content_type = models.ForeignKey(ContentType) # 默认与content type表就关联了 object_id = models.PositiveIntegerField() # 不会创建额外表,帮助你快速操作 content_object = GenericForeignKey('content_type', 'object_id')

    需求来咯

    1. 创建一个大课 & 给三个价格策略【笨办法】

    big_object = models.BigCourse.objects.create(name='Python')
    ct =models.ContentType.objects.filter(app_label='app02', model='bigcourse').first()
    models.PricePolicy.objects.create( period
    =30, price=10000, content_type=ct, object_id=big_object.id ) models.PricePolicy.objects.create( period=60, price=15000, content_type=ct, object_id=big_object.id ) models.PricePolicy.objects.create( period=90, price=18000, content_type=ct, object_id=big_object.id )

    简便方法

    # 在表中添加几行 【自己对照上面表结构找该放的位置吧】
    from django.contrib.contenttypes.fields import GenericForeignKey,
    # 不会创建额外表,帮助你快速操作
    content_object = GenericForeignKey('content_type', 'object_id')
    ============================================================

    big_object = models.BigCourse.objects.create(name='Linux') models.PricePolicy.objects.create( period=30, price=10000, content_object=big_object ) models.PricePolicy.objects.create( period=60, price=15000, content_object=big_object ) models.PricePolicy.objects.create( period=90, price=18000, content_object=big_object )

    2.获取所有的价格策略

    data_list = models.PricePolicy.objects.all()
    for item in data_list:
        item.id
        item.price
        # 自动找到与之有关的对象
        item.content_object

    3. 获取大课  语文(大)的所有的价格策略

    # 找表中合适的位置 自己添加
    from django.contrib.contenttypes.fields import GenericRelation
    # 不会创建额外表,帮助你快速操作
        price_policy = GenericRelation("PricePolicy")


    course_object = models.BigCourse.objects.filter(name='Python').first() price_object_list = course_object.price_policy.all()
  • 相关阅读:
    为Qtcreator 编译的程序添加管理员权限
    热备,冷备,云备
    最近面试java后端开发的感受:如果就以平时项目经验来面试,通过估计很难——再论面试前的准备
    进入2012 -- 回顾我走过的编程之路
    为什么中国程序员水平一直上不了层次?无非是这些原因!
    我是如何失去团队掌控的?
    后端开发甩锅奥义
    一个线程oom,进程里其他线程还能运行吗?
    架构师必备,带你弄清混乱的JAVA日志体系!
    IDEA一定要改的八条配置
  • 原文地址:https://www.cnblogs.com/a438842265/p/12597242.html
Copyright © 2011-2022 走看看