Fork me on GitHub

Django:内置组件Content-Type

12.Django组件之Content_Type

1.帮助我们生成了一张表,里面有所有表名.这样不再自建表在表中填表名,用Foreignkey获取
2.为了让我们快速进入插入数据,填写一个字段GenericForeignKey,(不用生成字段)
3.为了让我们快速反向查找,通过添加字段GenericRelation,(仅仅用于反向查找,不生成字段)
  • 内置组件,用于帮助我们做连表操作.需求展示:
  • 学习商城分学位课和普通课,学位课有老师提供在线解答,在线解答每个月费用如下表.普通课程不提供在线解答,只提供视频.但观看视频每月需要办理会员.现将2个价格策略表,合成一张表,如下:

  • 但是如果又有新的服务:比如开了VVIP课程,那么价格策略表又增加一个字段.这样以后添加新服务就要修改表结构.不断更改表结构.这样并不好.

  • 修改如下方法更加好:

  • 这样以后无论增加什么样服务,只需增加字段.这种方式适用于一张表同时关联多张表.

  • 表的创建models.py:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.contrib.contenttypes.models import ContentType
# Create your models here.

class Course(models.Model):
    """
    普通课程
    """
    title = models.CharField(max_length=32)

class DegreeCourse(models.Model):
    """
    学位课程
    """
    title = models.CharField(max_length=32)

class PricePolicy(models.Model):
    """
    价格策略
    """
    price = models.IntegerField()
    period = models.IntegerField()
    #ContentType会自己创建一张表,将所有表名称添加到该表中
    content_type = models.ForeignKey(ContentType,verbose_name="关联普通课或学位课表")
    object_id = models.IntegerField(verbose_name="关联普通课或学位课中的课程ID")
    #帮助你快速实现content_type操作,会自定将
    #obj = DegreeCourse.objects.filter(title="python全栈").first()
    #GenericForeignKey能够帮助我们:从数据库获取该对象obj的id和此对象对应content_type表里面的id.赋值到该表的
    #content_type和object_id
    content_object = GenericForeignKey("content_type","object_id")
    
#urls.py
url(r'^test/', views.test),
#views.py
from django.shortcuts import render,HttpResponse
from api import models
# Create your views here.

def test(request):
    """
    
    """
    #创建1个月的价格
    obj1 = models.DegreeCourse.objects.filter(title="python全栈").first()
    models.PricePolicy.objects.create(price=9.9,period=30,content_object=obj1)
	#创建2个月的价格
    obj2 = models.DegreeCourse.objects.filter(title="python全栈").first()
    models.PricePolicy.objects.create(price=15.9, period=60, content_object=obj2)
	#创建3个月的价格
    obj3 = models.DegreeCourse.objects.filter(title="python全栈").first()
    models.PricePolicy.objects.create(price=21.9, period=90, content_object=obj3)
    return HttpResponse("200 OK")
  • 添加成功:

  • 快速反向查找:

#需要在models.py被查找的表中添加字段:
price_policy_list = GenericRelation("PricePolicy")#仅仅用于反向查找,不生成字段


#在views.py
#获取所有课程的价格策略:
dero = models.DegreeCourse.objects.fliter(id=1).frist()
price_policys=dero.price_policy_list.all()
#获取到每个价格对象.
print(price_policys)#<QuerySet [<PricePolicy: PricePolicy object>, <PricePolicy: PricePolicy object>, <PricePolicy: PricePolicy object>]>
posted @ 2019-11-13 15:17  是阿凯啊  阅读(133)  评论(0编辑  收藏  举报