import os
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'idjango.settings')
import django
django.setup()
from idea import models
# 1.查询李白的手机号
# 方式1:
print(models.Author.objects.filter(name='李白').values('author_detail__phone'))
# <QuerySet [{'author_detail__phone': 1314}]>
# 方式2:
print(models.AuthorDetail.objects.filter(author__name='李白').values('phone'))
# <QuerySet [{'phone': 1314}]>
# 2.查询书籍主键为1的书籍名称和出版社名称
# 方式1:
print(models.Book.objects.filter(pk=1).values('title', 'publish__name'))
# <QuerySet [{'title': '望庐山瀑布', 'publish__name': 'North'}]>
# 方式2:
print(models.Publish.objects.filter(book__id=1).values('book__title', 'name'))
# <QuerySet [{'book__title': '望庐山瀑布', 'name': 'North'}]>
# 3.查询书籍主键为1的作者姓名
# 方式1:
print(models.Book.objects.filter(pk=1).values('authors__name'))
# <QuerySet [{'authors__name': '李白'}]>
# 方式2:
print(models.Author.objects.filter(book__id=1).values('name'))
# <QuerySet [{'name': '李白'}]>
# 查询书籍主键为1的作者的手机号 通过外键字段跨表查询
print(models.Book.objects.filter(pk=1).values('authors__author_detail__phone'))
# <QuerySet [{'authors__author_detail__phone': 1314}]>
django专栏 search 05.基于双下划线的跨表查询
最新推荐文章于 2024-11-05 00:06:40 发布