Django_基于双下划线——跨表查询

一对多:

  正向查询:

# 一对多:正向查询,查询三国演义这本书的出版社的名字     values("关联字段名__要查询的字段")
ret = models.Book.objects.filter(title="三国演义").values("publish__name")
print(ret)  # 查询到的出版社对象
# 获取对象中值的两种办法
print(ret[0]['publish__name'])
print(ret[0].get('publish__name'))

  反向查询:

# 一对多:反向查询,查询三国演义这本书的出版社的名字  filter(表名小写__关联的字段名="查询条件")
ret = models.Publish.objects.filter(book__title="三国演义").values("name")
print(ret)
print(ret[0]['name'])
print(ret[0].get('name'))

多对多:

  正向查询:

# 查询愚公移山这本书所有作者的名字  values(关联字段名__要查询的字段名)
ret = models.Book.objects.filter(title="愚公移山").values("authors__name")
print(ret)
print(ret[0]["authors__name"])
print(ret[1]["authors__name"])

  反向查询:

# 查询愚公移山这本书所有作者的名字  filter(表名小写__字段名="查询的条件")
ret = models.Author.objects.filter(book__title="愚公移山").values("name")
print(ret)
print(ret[0]["name"])
print(ret[1]["name"])

 一对一:

  正向查询:

# 一对一:查询女娲的手机号  values(关联字段名__要查询的字段名)
ret = models.Author.objects.filter(name="女娲").values("authordetail__telephone")
print(ret)
print(ret[0])
print(ret[0]["authordetail__telephone"])

  反向查询:

# 查询女娲的手机号    filter(表名小写__字段名="查询的条件")
ret = models.AuthorDetail.objects.filter(author__name="女娲").values("telephone")
print(ret)
print(ret[0])
print(ret[0]["telephone"])

 

posted @ 2020-04-20 00:20  手可摘星辰。  阅读(173)  评论(0编辑  收藏  举报