表结构设计方法

一对多关联2张表的方法

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey


class PricePolicy(models.Model):
    """价格与有课程效期表"""
    # 组件的作用: 可以通过两个字段让表和N张表创建 FK关系
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    # 数字字段 (正整数或0类型)
    object_id = models.PositiveIntegerField()
    # 不会再在数据库生成列,只用用帮助你进行添加和查询
    content_object = GenericForeignKey('content_type', 'object_id')


    # course = models.ForeignKey('Course')
    # 课程的周期
    valid_period_choices = ((1, '1天'), (3, '3天'),
                            (7, '1周'), (14, '2周'),
                            (30,'1个月'),
                            (60,'2个月'),
                            (90,'3个月'),
                            (180,'6个月'),(210,'12个月'),
                            (540, '18个月'), (720, '12个月'),
                            )
    valid_period = models.SmallIntegerField(choices=valid_period_choices)
    # 价格表
    price = models.FloatField()

创建方法

   models.PricePolicy.objects.create(
        # 学习周期
        valid_period=7,
        # 课程价格
        price=9.99,
        # 关键技术点, 关联了一个id为1的一个对象
        content_object=models.Course.objects.get(id=3)

    )
原文地址:https://www.cnblogs.com/Rivend/p/11989980.html