05 django組件:contenttype

一、django組件:contenttype

組件的做用:能夠經過兩個字段讓表和N張表建立FK關係python

一、專題課,學位課 如何關聯 過時時間??

方法1:分別建立 專題課--過時時間表 、學位課--過時時間表數據庫

方法2:專題課,學位課對應到一張過時時間表django

 方法3:過時時間表與 學位課,專業課,or 其餘課程,建立外鍵關係app

 

二、models初始表結構

 

$ python manage.py makemigrations $ python manage.py migrate

 

三、contenttype表

 

 

 

二、需求1:插入課程與過時時間

 一、方法1:ContentType

 

 

 二、方法2:GenericForeignKey

models表結構spa

 不會生成數據庫列3d

 

 view視圖code

 

 

三、需求2 :根據價格策略查找對應的表和數據

四、需求3:查詢過時時間和價格

 

五、contenttype組件的3件事

1張表跟多張表,動態的建立FK關係對象

2列實現多張表的FKblog

 

 其餘應用:get

  優惠券跟多張課程進行關聯

  公共評論表,與多張表進行關聯

六、代碼

django組件:contenttype
組件的做用:能夠經過兩個字段讓表和N張表建立FK關係

 models

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, on_delete=models.CASCADE)  # 關聯course or degree_course
    object_id = models.PositiveIntegerField() # 不會在數據庫生成列,只用於幫助你進行添加和查詢
    content_obj = GenericForeignKey('content_type','object_id') valid_period_choices = ( (1, '1天'), (3, '3天'), (7, '1周'), (14, '2周'), (30, '1個月'), (60, '2個月'), (90, '3個月'), (180, '6個月'), (360, '12個月'), (540, '18個月'), (720, '24個月'), ) valid_period = models.SmallIntegerField(choices=valid_period_choices) price = models.FloatField()

 

views

from django.shortcuts import render, HttpResponse from django.contrib.contenttypes.models import ContentType from app01 import models def test(request): """價格策略表中增長,查詢"""
    # 1.在價格策略表中添加一條數據
    # 方法1
    """ models.PricePolicy.objects.create( valid_period=7, price=6.6, content_type=ContentType.objects.get(model='course'), object_id=1 ) """

    # 方法2
    """ models.PricePolicy.objects.create( valid_period=14, price=9.9, content_obj=models.Course.objects.get(id=1) ) """

    # 2.根據某個價格策略對象,找到他對應的表和數據,如:管理課程名稱
    ''' price = models.PricePolicy.objects.get(id=2) print(price.content_obj.name) # 自動幫你找到 '''

    # 三、找到某個課程的全部價格策略
    obj = models.Course.objects.get(id=1) print(obj.policy_list.all()) for item in obj.policy_list.all(): print(item.id, item.valid_period, item.price) return HttpResponse('test...')
相關文章
相關標籤/搜索