Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django学习记录(十):Django by example -- Blog(六) #46

Open
PyxYuYu opened this issue Oct 2, 2016 · 0 comments
Open

Django学习记录(十):Django by example -- Blog(六) #46

PyxYuYu opened this issue Oct 2, 2016 · 0 comments
Labels

Comments

@PyxYuYu
Copy link
Owner

PyxYuYu commented Oct 2, 2016

The road to success is lined with many tempting parking spaces.

0x01 Django

  • Build a Blog Application
    • Retrieving objects

      • Django 有一套自己的 ORM 模型,检索一个对象的时候,可以用 get() 方法( Post.objects.get() ),每一个 Django 模型都有至少一个 manager ,默认的 manager 就是 objects ,检索一个表中所有的对象时,使用 all() 方法( Post.objects.all() )
    • QuerySet 只有被命令执行的时候,才会去执行

      • >>>all_post = Post.objects.all() 不会执行,因为 all_post 没有任何操作(没回显)
      • >>>Post.objects.all() 会执行,因为强迫其输出了结果(有回显)
    • Using the filter() method

      • 过滤一个 QuerySet,搜索指定条件,可以利用 filter() 方法
      • 单个条件检索,比如: Post.objects.filter(publish__year=2015)
      • 多个条件检索,比如: Post.objects.filter(publish__year=2015, author__username='admin')
      • 注意:此处的双下划线,后者可以是前者的方法,后者也可以是前者的属性
    • Using exclude()

      • 排除指定条件,用 exclude() 方法,比如: Post.objects.filter(publish__year=2015).exclude(title__startswith='Why')
    • Using order_by()

      • 排序用 order_by() 方法,比如:Post.objects.order_by('title')
      • 默认都是升序,降序的话,加前缀 - : Post.objects.order_by('-title')
    • Deleting objects

      • 删除一个对象,用 delete() 方法
      post = Post.objects.get(id=1)
      post.delete()
      
0x02 ORM

  • ORM 模型
    • Object Relational Mapping 对象关系映射
      • 为了解决面向对象和关系数据库存在的不匹配的现象的技术,简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象持久化到关系数据库中。
    • ORM 模型大概的思想就是对象和数据库中表的对应关系,一个对象就好比表中的一行数据,将对象的操作视为对表的操作,如增、删、改、查就是对表的同样操作,只需要封装一下就可以省下很多的重复劳动,通过 ORM 模型可以对代码上进行简洁,对数据库的操作通过 ORM 转换后执行,可以省掉很多复杂的 SQL 组装。
@PyxYuYu PyxYuYu added the Django label Oct 2, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant