Django(ORM查询联系题)

day70

练习题:http://www.cnblogs.com/liwenzhou/articles/8337352.html

 1 import os
 2 import sys
 3 if __name__ == '__main__':
 4     # 加载Django项目的配置信息  这一句就在manage.py文件中
 5     os.environ.setdefault("DJANGO_SETTINGS_MODULE",
 6                           "ormday70.settings")
 7     # 导入Django,并启动Django项目
 8     import django
 9     django.setup()
10     from app01 import models
11 
12     # 查找所有书名里包含花的书
13     ret = models.Book.objects.filter(title__contains="")
14     print(ret)
15     # 查找所有出版日期是2018年的书
16     ret = models.Book.objects.filter(publish_date__year=2019)
17     print(ret)
18     # 查找价格大于40元的书
19     ret = models.Book.objects.filter(price__gt=40)
20     print(ret)
21     # 找到在沙河的出版社
22     ret = models.Publisher.objects.filter(city="下沙")
23     print(ret)
24 
25     # distinct
26     # 查所有书关联的出版社
27     ret = models.Book.objects.all().values_list("publisher__name")
28     print("每本书的出版社分别是:", ret)
29     print("去重:", ret.distinct())  # 对QuerySet去重
30 
31     # 将所有的书按照价格倒叙排序
32     ret = models.Book.objects.all().order_by("price").reverse()
33     print(ret)
34     # 支持负号表示倒序
35     ret = models.Book.objects.all().order_by("-price")
36     print(ret)
37 
38     # 查询书名是繁花的书的出版社的city               #跨表到publisher
39     ret = models.Book.objects.filter(title="繁花").values("publisher__city")
40     print(ret)
41 
42     # 查询书名是沙河异闻录的书的作者的爱好(夸两张表)         #跨到Author再到detail字段
43     ret = models.Book.objects.filter(title="繁花").values("authors__detail__hobby")
44     print(ret)

 

练习:

结果:

<QuerySet [<Book: 繁花>]>
<QuerySet []>
<QuerySet [<Book: 繁花>, <Book: linux>, <Book: Python>]>
<QuerySet [<Publisher: 下沙出版社>]>
每本书的出版社分别是: <QuerySet [('下沙出版社',), ('下沙出版社',), ('马涧出版社',), ('兰溪出版社',)]>
去重: <QuerySet [('下沙出版社',), ('马涧出版社',), ('兰溪出版社',)]>
<QuerySet [<Book: Python>, <Book: 繁花>, <Book: linux>, <Book: C++>]>
<QuerySet [<Book: Python>, <Book: 繁花>, <Book: linux>, <Book: C++>]>
<QuerySet [{'publisher__city': '下沙'}]>
<QuerySet [{'authors__detail__hobby': '台球'}, {'authors__detail__hobby': '篮球'}]>

Process finished with exit code 0

 

posted on 2019-03-07 17:29  嘟嘟嘟啦  阅读(168)  评论(0编辑  收藏  举报

导航