Django内置的组件:content-type

django内置的组件,帮我们开发者做连表操作, 使用于一张表跟多张表关联。

使用:

  1. ContentType 用于关联表的名称
  2. GenericForeignKey 帮助快速实现content_type操作,将之对应起来
  3. GenericRelation 用于反向查找 不生成数据表
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType

# Create your models here.


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)


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_type操作
    content_object = GenericForeignKey('content_type', 'object_id')
# view
from django.shortcuts import render, HttpResponse
from app01 import models


def test(request):
    # 1 为学位课“python 全栈” 添加一个价格策略: 1个月9.9的数据
    obj = models.DegreeCourse.objects.filter(title='python全栈').first()
    models.PricePolicy.objects.create(price=9.9, period=30, content_object=obj)
    # 2 查找出课程ID 为1的所有的价格策略
    course = models.Course.objects.filter(id=1).first()
    price_policys = course.price_policy_list.all()
    print(price_policys, '这就是所有的价格')

    return HttpResponse('添加成功')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值