django之contenttype

  平时开发过程中,我们会经常遇到这么一个类似的场景,比如

    不同的课程,有不同的价格策略

    不同的课程可使用不同的优惠券(满减券,通用券,专用券)

    不同的评论区,支持的评论

 

  就拿  不同的课程,有不同的价格策略

    比如现在,有两种课程,一种是专题课程--21天学会python,网络编程..., 另一种就是学位课程--python全栈开发,linux自动化运维

    他们都有不同的价格策略,比如学1月 9.9元,3月27元等

    这两种课程提供的服务也是不一样的

  你会怎么设计表呢?

    既然是分两种课程,设计成两张表,专题课程表和学位课程表

    要一张价格策略表,想两种课程的价格策略在这一张表里,怎么搞?

      策略表和课程表为一对多,这里需要和专题课程表和学位课程表进行外键关联,所以需要table_id字段

      课程表的那个课程,course_id

      当然你还要考虑到,如果以后,我们可能还会扩展课程种类,我们可以再建一个存在 课程表名的表

 

  django提供了contenttype这么一个app,下面已经帮我们创建好 一个 存储表名的表ContentType

  不仅提供这么一个表,还方便了我们进行添加 table_id和course_id,另外方便我们课程表和策略表关联查询

from django.db import models
from django.contrib.contenttypes.models import ContentType

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation


class DegreeCourse(models.Model):
    """学位课程"""
    name = models.CharField(max_length=128, unique=True)
    course_img = models.CharField(max_length=255, verbose_name="缩略图")
    brief = models.TextField(verbose_name="学位课程简介", )


class Course(models.Model):
    """专题课程"""
    name = models.CharField(max_length=128, unique=True)
    course_img = models.CharField(max_length=255)

    # 不会在数据库生成列,只用于帮助你进行查询
    policy_list = GenericRelation("PricePolicy")


class PricePolicy(models.Model):
    """价格与有课程效期表"""
    content_type = models.ForeignKey(ContentType)  # 关联course or degree_course
    object_id = models.PositiveIntegerField()

    #不会在数据库生成列,只用于帮助你进行添加和查询
    content_object = GenericForeignKey('content_type', 'object_id')


    valid_period_choices = (
        (1, '1天'),
        (3, '3天'),
        (7, '1周'), (14, '2周'),
        (30, '1个月'),
        (60, '2个月'),
        (90, '3个月'),
        (180, '6个月'), (210, '12个月'),
        (540, '18个月'), (720, '24个月'),
    )
    valid_period = models.SmallIntegerField(choices=valid_period_choices)
    price = models.FloatField()

 操作

from django.shortcuts import render,HttpResponse
from app01 import models
from django.contrib.contenttypes.models import ContentType

def test(request):
    # 常规添加
    # models.PricePolicy.objects.create(
    #     valid_period=7,
    #     price=6.6,
    #     content_type=ContentType.objects.get(model='course'),
    #     object_id=1
    # )


    # 1.在价格策略表中添加一条数据(利用contenttype进行添加)
    # models.PricePolicy.objects.create(
    #     valid_period=14,
    #     price=9.9,
    #     content_object=models.Course.objects.get(id=1)
    # )

    # 2. 根据某个价格策略对象,找到他对应的表和数据,如:管理课程名称
    # price = models.PricePolicy.objects.get(id=2)
    # print(price.content_object.name) # 自动帮你找到

    # 3.找到某个课程关联的所有价格策略
    # obj = models.Course.objects.get(id=1)
    # for item in obj.policy_list.all():
    #     print(item.id,item.valid_period,item.price)
    #
    return HttpResponse('...')

 

  总结:一般需要foreignkey多张表都可以使用这种方式

 

posted @ 2018-11-20 18:32  财经知识狂魔  阅读(233)  评论(0编辑  收藏  举报