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...')
相关文章
相关标签/搜索