django之content_type

什么是content type:django内置的一个组件,这个组件帮忙做连表的操作。(混搭连表)

适用场景:适用于一张表与多张表同时做关联的时候。直接导入就可以使用了。

关联数据库说有的表;让我们可以快速插入数据,并且用反向查找能快速查找到数据。

models.py文件建立表

from django.db import models

# Create your models here.
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='关联的表名称')
    object_id=models.IntegerField(verbose_name='关联的表中的数据行的ID')

    content_object=GenericForeignKey('content_type','object_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)
"""

  views.py文件,进行数据插入和查看

from django.shortcuts import render,HttpResponse

# Create your views here.
from app01 import models

def test(request):
    # 1 为学位课python添加一个价格策略:一个月9.9
    # obj1=models.DegreeCourse.objects.filter(title='python').first()
    # models.PricePolicy.objects.create(price=9.9,period=30,content_object=obj1)
    #
    # obj1 = models.DegreeCourse.objects.filter(title='python').first()
    # models.PricePolicy.objects.create(price=19.9, period=60, content_object=obj2)
    #
    # obj1 = models.DegreeCourse.objects.filter(title='python').first()
    # models.PricePolicy.objects.create(price=29.9, period=90, content_object=obj3)

    # # 2 为学位课rest framework添加一个价格策略:一个月9.9
    # obj1=models.Course.objects.filter(title='rest framework').first()
    # models.PricePolicy.objects.create(price=9.9,period=30,content_object=obj1)
    #
    # obj2 = models.Course.objects.filter(title='rest framework').first()
    # models.PricePolicy.objects.create(price=19.9, period=60, content_object=obj2)
    #
    # obj3 = models.Course.objects.filter(title='rest framework').first()
    # models.PricePolicy.objects.create(price=29.9, period=90, content_object=obj3)

    # 3 根据课程的ID获取课程,并获取该课程的所有价格策略
    course=models.Course.objects.filter(id=1).first()
    price_policys=course.price_policy_list.all()
    print(price_policys)
    return HttpResponse('ok')
原文地址:https://www.cnblogs.com/fangjie0410/p/8534614.html