1. 程式人生 > >django之contenttype組件

django之contenttype組件

.text osi objects res from pri view length http

django組件contenttype使用條件:

  一張表要和n張表創建 ForeignKey 關系時;作用:可以通過兩個字段(表名稱和行ID)讓表和N張表創建FK關系

示例:

models.py:(表結構)

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這個字段只用於幫助你進行添加和查詢,不會在數據庫生成列
content_object = GenericForeignKey(content_type, object_id) # 相當於把 "content_type"和"object_id" 這兩個字段放到了 GenericForeignKey 的對象中了 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()

views.py:(使用)

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

def test(request):
    # 1.在價格策略表中添加一條數據
    # models.PricePolicy.objects.create(
    #     valid_period=7,
    #     price=6.6,
    #     content_type=ContentType.objects.get(model=‘course‘),
    #     object_id=1
    # )

    # models.PricePolicy.objects.create(
    #     valid_period=14,
    #     price=9.9,
    #     content_object=models.Course.objects.get(id=1)  # GenericForeignKey 添加操作; 找到 Course表 的表名和id 賦值給content_type,取到記錄行的id 賦值給 object_id,然後自動增加
    # )

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

    # 3.找到某個課程關聯的所有價格策略
    # obj = models.Course.objects.get(id=1)
    # for item in obj.policy_list.all():      # GenericRelation 查詢操作
    #     print(item.id,item.valid_period,item.price)
    #
    return HttpResponse(...)

django之contenttype組件