Django的contenttypes

这是一个django内置的表结构,为的就是通过两个字段让表和N张表创建FK关系。

比如说有两种不同课程,这两种课程都有价格周期和策略。如果最低级的则是给每个表创建一个价格策略。如果非要在同一个表内使用价格策略,

那么如上图那样,course_id跟专题课程做外键关联,学位课程为空,如果跟学位课程做关联,那么专题课程的ID又为空,如果很多门课程,那么

就需要在价格策略中写入很多的外键字段。

为了解决这种问题,django引入了一种方式就是django的contenttypes。

首先有下面的表结构:

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_object = GenericForeignKey('content_type', 'object_id')


    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()

这种结构就相当于下图:

另外建立一个表,存放表名称。

然后在价格策略表中放2个字段,一个字段就是表名,一个就是这个表中第几个数据。

比如course表中第一个数据21天入门。

表结构分析:

  content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)  # 关联course or degree_course
  object_id = models.PositiveIntegerField()  #这个就是课程表内有多少课程,这个约束不了,只能是个正整数。

 最后就是查询和增加的测试!

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) #这样得到就是Course表,而且id是1,这两个。自动帮你添加这两个值。 # )
# 2. 根据某个价格策略对象,找到他对应的表和数据,如:管理课程名称 # price = models.PricePolicy.objects.get(id=2) #ID为2的这条价格策略对象 # print(price.content_object.name) # 关联的是专题课程,想要显示专题课程的名称 21天入门
# 3.找到某个课程关联的所有价格策略 数据库中加这个 policy_list=GenericRelation("PricePolicy") # obj = models.Course.objects.get(id=1) # for item in obj.policy_list.all(): # print(item.id,item.valid_period,item.price) # # return HttpResponse('...')

 

 加的两个字段使用的关系以及使用django.content-type表的使用:

 不仅是价格策略,优惠券也会使用这个,比如2种类型的课程,买第一种课程的有优惠券,买第二种课程还可能有优惠券。

原文地址:https://www.cnblogs.com/geogre123/p/9803315.html