Django contenttypes组件

表结构

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)
    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
    # 字段找到与之相关联的对象BigCourse/SmallCourse
    item.content_object

获取大课python的所有价格策略

course_object = models.BigCourse.objects.filter(name='Python').first()
price_object_list = course_object.price_policy.all()
posted @ 2022-11-06 07:50  凫弥  阅读(31)  评论(0编辑  收藏  举报