ContentType组件

models部分

from django.db import models

# Create your models here.
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
class Course(models.Model):#免费课表
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=32)
    police=GenericRelation(to='PricePlicy')
class DegreeCourse(models.Model):#学位课表
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    police = GenericRelation(to='PricePlicy')
class LiteCourse(models.Model):#清课表
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    police = GenericRelation(to='PricePlicy')
class PricePlicy(models.Model):#价格策略表
    id = models.AutoField(primary_key=True)
    period=models.IntegerField()
    price=models.DecimalField(max_digits=8,decimal_places=2)
    object_id=models.IntegerField()
    content_type=models.ForeignKey(to=ContentType,null=True)
    content_obj=GenericForeignKey()

测试部分相当于views部分

import os

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffy_city.settings")
    #蓝色部分与views所在文件夹名相同
    import django

    django.setup()

    from api import models
    from django.contrib.contenttypes import models as co_model

    为django免费课,添加三个价格策略
    原始方式,比较麻烦
    course = models.Course.objects.get(pk=1)
    table_id = co_model.ContentType.objects.get(model='course')
    ret = models.PricePolicy.objects.create(period=1, price=9.9, course_id=course.pk, table_id=table_id)
    ret = models.PricePolicy.objects.create(period=7, price=19.9, course_id=course.pk, table_id=table_id)
    ret = models.PricePolicy.objects.create(period=14, price=29.9, course_id=course.pk, table_id=table_id)
    

    contenttype提供的快速插入的方法
    
    course = models.Course.objects.get(pk=1)
    ret=models.PricePolicy.objects.create(period=30, price=199.9,content_obj=course)

    为学位课,添加一个价格策略
    degree_course=models.DegreeCourse.objects.get(pk=1)
    ret = models.PricePolicy.objects.create(period=180, price=28888, content_obj=degree_course)

    查询所有价格策略,并且显示对应的课程名称
    price_policy_list=models.PricePolicy.objects.all()
    for price_policy in price_policy_list:
    
        print(type(price_policy.content_obj))

        print(price_policy.content_obj.name)
    查询django课程信息的所有价格策略
    course=models.Course.objects.get(pk=1)
    policy_list 就是django这门课所有的价格策略对象
    policy_list=course.policy.all()
    for policy in policy_list:
         print(policy.price)

    查询python全栈开发的所有价格策略
    degree_course=models.DegreeCourse.objects.get(pk=1)
    policy_list=degree_course.policy.all()
    for policy in policy_list:
        print(policy.price)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值