Django应用之content type(app应用之一django.contrib.contenttypes)

当一张表作为多个表的FK(主键),并且只能选择其中一个或者几个时,就可以使用content_type表;例如下图的数据关系,因此就可以使用content_type表来将表与表中的对象进行关联,从而做到不增加列字段的情况下增加FK关系。

  在使用content_type表时,需要在FK表中增加content_type作为FK字段,并增加GenericForeignKey便于价格策略表记录的建立以及对应的课程的查找。

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
class degreecourse(models.Model):
    title = models.CharField(max_length=32)
    #仅用于反向查找
    price_1 = GenericRelation(to='Price_1')

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

class Price_1(models.Model):
    price= models.IntegerField()
    period = models.IntegerField()
    content_type = models.ForeignKey(ContentType,verbose_name='...')
    object_id = models.IntegerField()
    content_list = GenericForeignKey('content_type','object_id')
View Code--- 对应的模型类
def table(request):
    #插入
    # obj = degreecourse.objects.get(title='python')
    # Price_1.objects.create(price=15,period=30,content_list=obj)
    #
    # obj = degreecourse.objects.get(title='python')
    # Price_1.objects.create(price=20, period=60, content_list=obj)
    #
    # obj = degreecourse.objects.get(title='python')
    # Price_1.objects.create(price=25, period=90, content_list=obj)

    # 查找
    obj = degreecourse.objects.get(id=1)
    #print(obj)
    print(len(obj.price_1.all()))
    return HttpResponse('xxx')
View Code--对应的视图类

网上虽然有很多讲这个的,但是,当我用的时候,一边看着别人的,码着自己的,然后就发现了其中的很多错误,

这里有个我踩过的坑,就是这个

content_type,object_id,不能使用其他变量来做更换】

【如果有做变换,就报错(Cannot resolve keyword 'content_type' into field. Choices are: content_list, content_type1, content_type1_id, id, object_id, period, price),如果有类似的报错,就需要注意是否变量名书写错误】,

暂时还没看内部源码实现过程,之后再慢慢补源码过程

原文地址:https://www.cnblogs.com/Skyda/p/10105151.html