天天看點

Django:ContentType元件

本文目錄:

一、項目背景

二、版本一

三、版本二

四、終極版(使用ContentType)

  luffy項目,有課程有學位課(不同的課程字段不一樣),價格政策

  問題:1.如何設計表結構,來表示這種規則

     2.為專題課,添加三個價格政策

     3.查詢所有的價格政策,并且顯示對應的課程名稱

        4.通過課程id,擷取課程資訊和價格政策

  一個課程表,包含學位課和專題課,一個價格政策表,一對多關聯

Django:ContentType元件

學位課表,專題課表,周末表,價格政策表(在價格政策表中加入多個FK跟課程表做關聯):後期再加其他課程,可維護性差

Django:ContentType元件

通過Django提供的ContentType表,來建構

Django:ContentType元件
Django:ContentType元件

 models層:

from django.db import models

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


class Course(models.Model):
    title = models.CharField(max_length=32)
    # 不會在資料庫中生成字段,隻用于資料庫操作
    # policy = GenericRelation('PricePolicy',object_id_field='object_id',content_type_field='contentType')


class DegreeCourse(models.Model):
    title = models.CharField(max_length=32)


class PricePolicy(models.Model):
    # 跟ContentType表做外鍵關聯
    contentType = models.ForeignKey(to=ContentType)
    # 正數
    object_id = models.PositiveIntegerField()

    # 引入一個字段,不會在資料庫中建立,隻用來做資料庫操作
    # content_obj = GenericForeignKey('contentType', 'object_id')

    period = models.CharField(max_length=32)
    price = models.FloatField()      

views層:

from app01 import models
def test(request):
    import json
    # 方式一插入價格規則
    # ret=models.ContentType.objects.filter(model='course').first()
    # course=models.Course.objects.filter(pk=1).first()
    # print(ret.id)
    # models.PricePolicy.objects.create(period='30',price=100,object_id=course.id,contentType_id=ret.id)

    # 方式二插入價格規則
    # course=models.Course.objects.filter(pk=1).first()
    # # content_obj=course  會自動的把課程id放到object_id上,并且去ContentType表中查詢課程表的id,放到contentType上
    # models.PricePolicy.objects.create(period='60',price=800,content_obj=course)
    # 增加學位課,價格規則
    # degreecourse = models.DegreeCourse.objects.filter(pk=1).first()
    # models.PricePolicy.objects.create(period='60', price=800, content_obj=degreecourse)

    # 查詢所有價格政策,并且顯示對應的課程名稱
    # ret=models.PricePolicy.objects.all()
    # for i in ret:
    #     print(i.price)
    #     print(i.period)
    #     # content_obj 就是代指關聯的課程,或者學位課程的那個對象
    #     print(type(i.content_obj))
    #     print(i.content_obj.title)

    # 通過課程id,擷取課程資訊和價格政策
    course=models.Course.objects.filter(pk=1).first()
    print(course.policy.all())