Django-一对一表跨表查询
一对一表跨表查询
准备数据
员工信息表:id、姓名、年龄
工资表:id、员工id、薪资(员工id与员工信息表的id一一对应)
# 建表
class UserInfo(models.Model):
name = models.CharField(max_length=32,null=True)
age = models.IntegerField()
class Private(models.Model):
salary = models.CharField(max_length=32,null=True)
sp = models.OneToOneField('UserInfo') # OneToOneField对应员工表信息表的id
# 添加数据
info = [
models.UserInfo(name='aaa',age=18),
models.UserInfo(name='bbb',age=19),
models.UserInfo(name='ccc',age=20),
models.UserInfo(name='ddd',age=21),
models.UserInfo(name='eee',age=22)
]
models.UserInfo.objects.bulk_create(info)
pri = [
models.Private(salary='5000',sp_id=1),
models.Private(salary='6000',sp_id=2),
models.Private(salary='4000',sp_id=3),
models.Private(salary='5000',sp_id=4),
models.Private(salary='7000',sp_id=5),
]
models.Private.objects.bulk_create(pri)
查询语句
# 查询name为aaa的薪资。从目表查子表数据
res = models.UserInfo.objects.filter(name='aaa').first()
print(res.private.salary)
# 查询薪资为5000的员工姓名
res = models.Private.objects.filter(salary=5000).all()
for item in res:
print(item.sp.name)