一.关于content_type 使用

1.引入模块在models

from django.db import models
from django.contrib.contenttypes.models import ContentType #使用ContentType 
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation #正向查询, 反向查询

2. 创建数据库,普通课程, 私人课程, 价格策略

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)
    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="关联的表名称",on_delete=models.CASCADE)
    object_id = models.IntegerField(verbose_name="关联表的数据行ID")

    content_object = GenericForeignKey("content_type", "object_id") #通过找到content_type 找到 关联的表名, object_id 找到行id

最后创建数据库

3.在test.views 增加,反向查询

def test(request):
    obj = models.DegreeCourse.objects.filter(title="老人与海").first()#找到对象
    models.PricePolicy.objects.create(price=9.9, period=30, content_object=obj)# content_object=obj
    obj2 = models.DegreeCourse.objects.filter(title="老人与海").first()
    models.PricePolicy.objects.create(price=19.9, period=30, content_object=obj2)
    obj3 = models.DegreeCourse.objects.filter(title="老人与海").first()
    models.PricePolicy.objects.create(price=29.9, period=30, content_object=obj3)

    # 反向查询
    course = models.DegreeCourse.objects.filter(id=1).first()

    price_policys = course.price_policy_list.all()
    print(price_policys)

    return HttpResponse("OK")

结果

django model content_type 使用

django model content_type 使用

 

 

文章引用 https://www.cnblogs.com/c-x-m/articles/8991616.html#autoid-0-0-0