Django中object.all

前言

先抛出一个问题。银行就相当于一个数据库,你去银行取钱存钱办卡销卡,是你告诉银行柜员方便还是你自己去操作电脑办卡取卡方便?(你还不一定会,假设自动存款机还没发明),object在数据库中就相当于银行里得银行柜员。

步入正题:

在django中的view.py中,我们可能回经常见到  book_set= Book.objects.all(),book_list = Book.objects.get()?

让我们疑惑的问题是,objects是个什么东西,book_set 和book_list 又是个神马东西?

object是Manager类型的对象,定义在from django.db import models中,是默认生成的,也就是objects = Modes.Manage() 。用途是数据库和模型对象交互的接口(api)。book_set返回的是个集合,book_list返回的是个列表。book = Book.objects.all(),这个翻译成银行得话就是,一个叫BOOK得人来到银行,通过一个名叫objects得柜员,查询BOOK得银行余额和银行卡信息,结果得到一个queryset对象

在book =BOOK.objects.get()或者book = BOOK.objects.all()中

  • BOOK是类名,就是你在model中创建的类
  • objects是django默认的管理器对象,就是刚才的比喻中的银行柜员,帮你完成各种操作。
  • get()或者all()是API,一种内置函数,也就是比喻钟银行柜员可以帮助我们完成的各种具体业务,不同的业务调用不同的API就可以了。
  • book通过all()得到的就是要给queryset()对象,也就是查询对象集合。

一,QuerySet 对象的创建方法

>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()
 
总之,一共有四种方法
# 方法 1
Author.objects.create(name="WeizhongTu", email="tuweizhong@163.com")
 
# 方法 2
twz = Author(name="WeizhongTu", email="tuweizhong@163.com")
twz.save()
 
# 方法 3
twz = Author()
twz.name="WeizhongTu"
twz.email="tuweizhong@163.com"
twz.save()
 
# 方法 4,首先尝试获取,不存在就创建,可以防止重复
Author.objects.get_or_create(name="WeizhongTu", email="tuweizhong@163.com")
# 返回值(object, True/False)

备注:前三种方法返回的都是对应的 object,最后一种方法返回的是一个元组,(object, True/False),创建时返回 True, 已经存在时返回 False

对比得知,object这个管理器对象帮了我们很多忙,我们不用实例化对象,不用save(),而是交给Author.object去实现。

举个例子吧,如果我们把数据库比作银行,那么object对象就相当于柜员,能帮助你处理各种业务。如果没有得话,去银行取钱,我们得自己登记,自己去金库拿钱,记账,锁门.........不太现实吧。同理,你去数据库取个数据,没有objects对象,是不是很麻烦?

其实换个角度来讲,你去银行办理得一些业务,是银行柜员帮你在银行得数据库里进行得增删改查操作,银行柜员得名字可以叫object(默认得名字),当然也可以叫小李,小王,不过你得自定义罢了。xiaoli = models.Manage()也是可以得。

你看看,此时此刻,有没有认识到,一切皆对象,这个面向对象编程得伟大之处。

二,Django中查询常用的API

# 查询相关API:

#  <1>filter(**kwargs):      它包含了与所给筛选条件相匹配的对象

#  <2>all():                 查询所有结果

#  <3>get(**kwargs):         返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。

#-----------下面的方法都是对查询的结果再进行处理:比如 objects.filter.values()--------

#  <4>values(*field):        返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列 model的实例化对象,而是一个可迭代的字典序列
                                     
#  <5>exclude(**kwargs):     它包含了与所给筛选条件不匹配的对象

#  <6>order_by(*field):      对查询结果排序

#  <7>reverse():             对查询结果反向排序

#  <8>distinct():            从返回结果中剔除重复纪录

#  <9>values_list(*field):   它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列

#  <10>count():              返回数据库中匹配查询(QuerySet)的对象数量。

# <11>first():               返回第一条记录

# <12>last():                返回最后一条记录

#  <13>exists():             如果QuerySet包含数据,就返回True,否则返回False。

另外关于ApI,给大家推荐一篇不错得文章

https://blog.csdn.net/cumtdeyurenjie/article/details/80211896

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Table of Contents Preface 1 Chapter 1: Introduction to Django 7 MVC pattern in web development 7 Why Python? 8 Why Django? 9 Tight integration between components 10 Object-Relational Mapper 10 Clean URL design 10 Automatic administration interface 10 Advanced development environment 10 Multilingual support 11 History of Django 11 Summary 12 Chapter 2: Getting Started 13 Installing the required software 13 Installing Python 13 Installing Python on Windows 14 Installing Python on UNIX/Linux 14 Installing Python on Mac OS X 15 Installing Django 15 Installing Django on Windows 15 Installing Django on UNIX/Linux and Mac OS X 16 Installing a database system 17 Creating your first project 18 Creating an empty project 18 Setting up the database 20 Launching the development server 22 Summary 23 This material is copyright and is licensed for the sole use by Richard Ostheimer on 15th June 2009 2205 hilda ave., , missoula, , 59801 Table of Contents [ ii ] Chapter 3: Building a Social Bookmarking Application 25 A word about Django terminology 25 URLs and views: creating the main page 26 Creating the main page view 26 Creating the main page URL 27 Models: designing an initial database schema 31 The link data model 32 The user data model 35 The bookmark data model 36 Templates: creating a template for the main page 38 Putting it all together: generating user pages 40 Creating the URL 40 Writing the view 41 Designing the template 42 Populating the model with data 44 Summary 45 Chapter 4: User Registration and Management 47 Session authentication 47 Creating the login page 48 Enabling logout functionality 53 Improving template structure 54 User registration 59 Django forms 59 Designing the user registration form 60 Account management 68 Summary 69 Chapter 5: Introducing Tags 71 The tag data model 72 Creating the bookmark submission form 75 Restricting access to logged-in users 80 Methods for browsing bookmarks 81 Improving the user page 83 Creating a tag page 85 Building a tag cloud 87 A word on security 90 SQL injection 91 Cross-Site Scripting (XSS) 91 Summary 93 This material is copyright and is licensed for the sole use by Richard Ostheimer on 15th June 2009 2205 hilda ave., , missoula, , 59801 Table of Contents [ iii ] Chapter 6: Enhancing the User Interface with AJAX 95 AJAX and its advantages 96 Using an AJAX framework in Django 97 Downloading and installing jQuery 98 The jQuery JavaScript framework 99 Element selectors 100 jQuery methods 100 Hiding and showing elements 101 Accessing CSS properties and HTML attributes 102 Manipulating HTML documents 103 Traversing the document tree 103 Handling events 104 Sending AJAX requests 105 What next? 105 Implementing live searching of bookmarks 105 Implementing basic searching 106 Implementing live searching 109 Editing bookmarks in place 112 Implementing basic bookmark editing 113 Implementing in-place editing of bookmarks 117 Auto-completion of tags 125 Summary 129 Chapter 7: Voting and Commenting 131 Sharing bookmarks on the main page 131 The SharedBookmark data model 132 Modifying the bookmark submission form 133 Browsing and voting for shared bookmarks 135 The popular bookmarks page 141 Commenting on bookmarks 144 Enabling the comments application 144 Creating a view for comments 145 Displaying comments and a comment form 147 Creating comment templates 149 Summary 153 Chapter 8: Creating an Administration Interface 155 Activating the administration interface 155 Customizing the administration interface 159 Customizing listing pages 160 Overriding administration templates 162 This material is copyright and is licensed for the sole use by Richard Ostheimer on 15th June 2009 2205 hilda ave., , missoula, , 59801 Table of Contents [ iv ] Users, groups, and permissions 164 User permissions 164 Group permissions 165 Using permissions in views 166 Summary 167 Chapter 9: Advanced Browsing and Searching 169 Adding RSS feeds 170 Creating the recent bookmarks feed 170 Customizing item fields 174 Creating the user bookmarks feed 175 Linking feeds to HTML pages 178 Advanced searching 179 Retrieving objects with the database API 180 Advanced queries with Q objects 183 Improving the search feature 184 Organizing content into pages (pagination) 185 Summary 190 Chapter 10: Building User Networks 191 Building friend networks 191 Creating the friendship data model 192 Writing views to manage friends 195 The friends list view 195 Creating the add friend view 198 Inviting friends via email 201 The invitation data model 202 The Invite A Friend form and view 205 Handling activation links 207 Improving the interface with messages 211 Summary 214 Chapter 11: Extending and Deploying 217 Internationalization (i18n) 217 Marking strings as translatable 218 Creating translation files 221 Enabling and configuring the i18n system 223 Improving performance with caching 226 Enabling caching 227 Local memory caching 227 Database caching 227 File system caching 227 Memcached 227 This material is copyright and is licensed for the sole use by Richard Ostheimer on 15th June 2009 2205 hilda ave., , missoula, , 59801 Table of Contents [ v ] Configuring caching 228 Caching the whole site 228 Caching specific views 229 Unit testing 229 The test client 230 Testing the registration view 232 Deploying Django 236 The production web server 237 The production database 237 Turning off debug mode 237 Changing configuration variables 238 Setting error pages 238 Summary 239 Chapter 12: What Next? 241 Custom template tags and filters 242 Model managers and custom SQL 243 Generic views 244 Contributed sub-frameworks 245 Flatpages 245 Sites 246 Markup filters 246 Humanize 247 Sitemaps 247 Cross-Site Request Forgery protection (CSRF) 247 Message system 248 Subscription system 249 User scores 249 Summary 250 Index 251

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网络毒刘

授人玫瑰,手有余香。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值