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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2019-03-30 (二十五)微信小程序的登陆 实际逻辑