django model content_type 使用

本文深入探讨了 Django 框架中 content_type 的使用方法,包括如何在 models 中引入和使用 ContentType 和 GenericForeignKey,实现多态关联和反向查询。通过具体实例,如创建课程和价格策略模型,演示了如何利用 content_type 进行数据库操作。

一.关于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")

结果

 

 

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

转载于:https://www.cnblogs.com/zhangqing979797/p/10105157.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值