Djangoの残りのフレームワーク框架-content型

テーブル構造の議論:

定価ポリシーテーブルを持つ2つの異なる価格戦略を記録します

 

コンテンツ・タイプの原則:

 

テーブル名に行を追加し、異なるコースの価格を記録するためのテーブルを使用します

注:テーブルに関連付けられた複数のテーブルの場合には

 

 

 自動的にこのような構成を生成します:

CONTENT_TYPE:Djangoの開発者でも、テーブルを操作していないのに役立つ組み込みコンポーネント
              でも、テーブル操作:ノーマルとのForeignKey、OneToOne、多対多
              でも先輩手術台:CONTENT_TYPE


初版:このテーブルに関連付けられている従来の方法を生成します
クラスコース(models.Model):
	「」「普通のコース」「」
	タイトル= models.CharField(MAX_LENGTH = 32)

クラスDegreeCourse(models.Model):
	「」「学位コース」「」
	タイトル= models.CharField(MAX_LENGTH = 32)

クラスPricePolicy(models.Model):
	「」「価格戦略」「」
	価格= models.IntegerField()
	期間= models.IntegerField()

	TABLE_NAME = models.CharField(verbose_name = "テーブル名協会")
	OBJECT_ID = models.CharField(verbose_name = "データテーブル関連付けられた行ID")

第二版:contentypeの使用に関連した複数のテーブルを行います
django.contrib.contenttypes.fieldsからGenericForeignKey、GenericRelationをインポート
from django.contrib.contenttypes.models import ContentType
class Course(models.Model):
	"""普通课"""
	title = models.CharField(max_length=32)
	# 用于反向查找
	price_policy_list = GenericRelation("PricePolicy")

class DegreeCourse(models.Model):
	"""学位课"""
	title = models.CharField(max_length=32)
	# 用于反向查找
	price_policy_list = GenericRelation("PricePolicy")

class PricePolicy(models.Model):
	"""价格策略"""
	price = models.IntegerField()
	period = models.IntegerField()
    #关联到ContentType表 
	table_name = models.ForeignKey(ContentType, verbose_name="关联普通课表或者学位课表")
	object_id = models.IntegerField(verbose_name="关联普通课表或者学位课表中的数据行ID")

	#1. 为学位课PYTHON全栈 添加一个价格策略 一个月 9.9
	#obj = DegreeCourse.objects.filter(title="PYTHON全栈").first()
	#obj.id
	#cobj = ContentType.objects.filter(model = 'course').first()
	#cobj.id
	#PricePolicy.objects.create(price='9.9',period='30',content_type_id=cobj.id,object_id=obj.id)
	#以上操作用下面代替
	content_object = GenericForeignKey('content_type', 'object_id')

# 添加view例子

def test(request):
	#1. 为学位课PYTHON全栈 添加一个价格策略 一个月 9.9
	obj1 = DegreeCourse.objects.filter(title="PYTHON全栈").first()
	PricePolicy.objects.create(price=9.9,period='一个月',content_type=obj1)

	obj2 = DegreeCourse.objects.filter(title="PYTHON全栈").first()
	PricePolicy.objects.create(price=39.9,period='二个月',content_type=obj2)

	obj3 = DegreeCourse.objects.filter(title="PYTHON全栈").first()
	PricePolicy.objects.create(price=59.9,period='三个月',content_type=obj3)

	#2. 根据课程ID获取课程, 并获取该课程的所有价格策略
	course = models.Course.objects.filter(id=1).first()
	price_policys = course.price_policy_list.all()

	return HttpResponse("添加成功")

  

 

おすすめ

転載: www.cnblogs.com/kuku0223/p/11353763.html