Django高级-ContentType

一 项目背景

路飞学成项目,有课程,学位课(不同的课程字段不一样),价格策略

问题,1 如何设计表结构,来表示这种规则
  2 为专题课,添加三个价格策略
3 查询所有价格策略,并且显示对应的课程名称
4 通过课程id,获取课程信息和价格策略

二 版本一

一个课程表,包含学位课和专题课,一个价格策略表,一对多关联

img

三 版本二

学位课表,专题课表,装逼课表,价格策略表(在价格策略课表中加入多个FK跟课程表做关联):后期再加其它课程,可维护性差

img

四 最终版(使用ContentType)

通过Django提供的ContentType表,来构建

img

models层创建:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.db import models

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation


class Course(models.Model):
title = models.CharField(max_length=32)
# 不会在数据库中生成字段,只用于数据库操作
# policy = GenericRelation('PricePolicy',object_id_field='object_id',content_type_field='contentType')


class DegreeCourse(models.Model):
title = models.CharField(max_length=32)


class PricePolicy(models.Model):
# 跟ContentType表做外键关联
contentType = models.ForeignKey(to=ContentType)
# 正数
object_id = models.PositiveIntegerField()

# 引入一个字段,不会在数据库中创建,只用来做数据库操作
# content_obj = GenericForeignKey('contentType', 'object_id')

period = models.CharField(max_length=32)
price = models.FloatField()

views层:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from app01 import models
def test(request):
import json
# 方式一插入价格规则
# ret=models.ContentType.objects.filter(model='course').first()
# course=models.Course.objects.filter(pk=1).first()
# print(ret.id)
# models.PricePolicy.objects.create(period='30',price=100,object_id=course.id,contentType_id=ret.id)

# 方式二插入价格规则
# course=models.Course.objects.filter(pk=1).first()
# # content_obj=course 会自动的把课程id放到object_id上,并且去ContentType表中查询课程表的id,放到contentType上
# models.PricePolicy.objects.create(period='60',price=800,content_obj=course)
# 增加学位课,价格规则
# degreecourse = models.DegreeCourse.objects.filter(pk=1).first()
# models.PricePolicy.objects.create(period='60', price=800, content_obj=degreecourse)

# 查询所有价格策略,并且显示对应的课程名称
# ret=models.PricePolicy.objects.all()
# for i in ret:
# print(i.price)
# print(i.period)
# # content_obj 就是代指关联的课程,或者学位课程的那个对象
# print(type(i.content_obj))
# print(i.content_obj.title)

# 通过课程id,获取课程信息和价格策略
course=models.Course.objects.filter(pk=1).first()
print(course.policy.all())




return render(request,'test.html')