三篇文章带你了解基础、进阶、高端篇Django ORM操作(进阶)
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理
本文章来自腾讯云 作者:Python进阶者
代码
book = models.Book.objects.filter(title="<<大明帝国>>").first() print(f"book类型:{type(book)}") print(f"id:{book.id}") print(f"书名:{book.title}") print(f"价格:{book.price}") print(f"书名:{book.PublishDate}") print(f"出版社:{book.publish}") # 外键字段
执行结果
代码
print(f"出版社类型:{type(book.publish)}") # <class 'web.models.Publish'> # book.publish已经是models.Publish对象,所以可以自由调里面的属性 print(f"出版社电话:{book.publish.phone},")
代码
# 查询邮电出版社 publish_obj = models.Publish.objects.filter(title="邮电出版社").first() # 获取出版社id publish_id = publish_obj.id # 查询publish_id为出版社id的 book_list = models.Book.objects.filter(publish_id=publish_id) print(book_list)
执行结果
其实,还有一种方法:通过一个对象,反向查多个对象。
代码
publish_obj = models.Publish.objects.filter(title="邮电出版社").first() book_list = publish_obj.book_set.all() print(book_list)
执行结果
代码
book_list = models.Book.objects.filter(publish__title="邮电出版社") print(book_list)
ret = models.BookManyAuthor.objects.filter(book__publish__title="邮电出版社") print(ret)
跨了book表又跨了publish表
执行结果
执行结果
代码
# 查询邮电出版社 publish = models.Publish.objects.filter(title="邮电出版社").first() print(publish) # 反向一对多 book_list = publish.book_set.all() print(book_list)
执行结果
别名方式
models.py
代码
# 查询邮电出版社 publish = models.Publish.objects.filter(title="邮电出版社").first() print(publish) # 反向一对多 book_list = publish.book_list.all() print(book_list)
执行结果
代码
# 举例而已,后面filter里面可以是其他 或 的条件 book1 = models.Book.objects.filter(title="<<大明帝国>>").filter(price="99") # 效果同上 book2 = models.Book.objects.filter(title="<<大明帝国>>",price="99") print(book1) print(book2)
执行结果