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()