表结构

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
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)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
添加数据
创建一个大课 & 三个价格策略(笨办法)
big_object = models.BigCourse.objects.create(name='Python')
ct =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
)
创建一个大课 & 三个价格策略(简便方法)
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
)
创建一个小课 & 三个价格策略(简便方法)
small_object = models.SmallCourse.objects.create(name='CRM')
models.PricePolicy.objects.create(
period=30,
price=10000,
content_object=small_object
)
models.PricePolicy.objects.create(
period=60,
price=15000,
content_object=small_object
)
models.PricePolicy.objects.create(
period=90,
price=18000,
content_object=small_object
)
获取所有价格策略
data_list = models.PricePolicy.objects.all()
for item in data_list:
item.id
item.price
item.content_object
获取大课python的所有价格策略
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 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具