django contenttypes组件

本文介绍了如何使用Django的GenericForeignKey实现课程与价格策略的高效关联,通过内容类型自动匹配,简化了Python大课和小课价格策略的管理。之前的冗余代码被重构,展示了如何为Python课程创建价格策略及获取策略实例的方法。
摘要由CSDN通过智能技术生成

1. 模拟需求:课程&价格设计方案

1.1 初版

1.2 中级

1.3 利用django contenttypes

 1.3.1 表

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='u')
 price = models.FloatField(verbose_name='价格')
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 # 不会额外创建列,快速操作使用
 content_object = GenericForeignKey('content_type', 'object_id')

1.3.2 添加大课数据(content_object自动帮你找到所需的值,添加进去)

之前

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

1.3.3 获取所有的python的价格策略

之前

data_list = models.PricePolicy.objects.all()
for item in data_list:
 item.id
 item.price
 item.content_object

现在

course_object = models.BigCourse.objects.filter(name='Python').first()
price_object_list = course_object.price_policy.all()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑猪去兜风z1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值