ContentType Django自带的表

models.py中

from django.db import models
from django.contrib.contenttypes.fields import 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()

    content_type = models.ForeignKey(ContentType, verbose_name='关联的表名称') # 7,8 表名称
    object_id = models.IntegerField(verbose_name='关联的表中的数据行的ID')   #
    # 帮助你快速实现content_type操作
    content_object = GenericForeignKey('content_type', 'object_id')
# 为学位课“Python全栈”添加一个价格策略:一个月 9.9
原先方法:
obj = DegreeCourse.objects.filter(title='Python全栈').first()
cobj = ContentType.objects.filter(model='course').first()
PricePolicy.objects.create(price='9.9',period='30',content_type_id=cobj.id,object_id=obj.id)  

现在方法:
obj = DegreeCourse.objects.filter(title='Python全栈').first()
PricePolicy.objects.create(price='9.9',period='30',content_object=obj)

view.py

#  查询操作
from django.shortcuts import render,HttpResponse from app01 import models def test(request): # 根据课程ID获取课程, 并获取该课程的所有价格策略 course = models.Course.objects.filter(id=1).first() price_policys = course.price_policy_list.all() # 查询操作
print(price_policys) return HttpResponse('...')

 

posted @ 2018-03-14 10:17  JAYWX  阅读(212)  评论(0编辑  收藏  举报