Django模型类的关系和关系的查询

新建Herolnfo类

class Heroinfo(models.Model):
    hname=models.CharField(max_length=20) #英雄名称
    hgender=models.BooleanField(default=True)  #性别 为bool类型,且默认值为true true代表女 false代表男
    hcomment=models.CharField(max_length=128)
    hbook =models.ForeignKey('Bookinfo')  #外键,生成一对多的关系

生成迁移文件

python manage.py makemigrations

迁移表

python manage.py migrate

打开shell

python manage.py shell

在shell 中执行下列语句:

# 引入俩个模型类

from booktest.models import Bookinfo,Heroinfo

b=Bookinfo()

b.btitle="九行天歌"

from datetime import date

b.bpub_date=date(2020,7,28)

b.save()

h=Heroinfo()

h.hname="师哥"

h.hgender=False

h.hcomment="百步飞剑"

# 设置hook的外键

h.hbook=b

h.save()

原文地址:https://www.cnblogs.com/laochun/p/13397299.html