Django官方文档Model层之数据操作(主要是查询)

1.新建

1 >>> from blog.models import Blog
2 >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
3 >>> b.save()

 

通过实例化来建立的对象后需要调用save()方法,才能保存到数据库。如果想建立和保存一步到位,用create方法吧。

2.保存:

 1 >>> b5.name = 'New name' 2 >>> b5.save() 

  保存外键:

1 >>> from blog.models import Entry
2 >>> entry = Entry.objects.get(pk=1)
3 >>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
4 >>> entry.blog = cheese_blog   #把cheese_blog直接赋值给entry对象的外键
5 >>> entry.save()     #必须记得保存

  保存多对多关系add:

1 >>> john = Author.objects.create(name="John")      #新建Author对象
2 >>> paul = Author.objects.create(name="Paul")       
3 >>> george = Author.objects.create(name="George")
4 >>> ringo = Author.objects.create(name="Ringo")    
5 >>> entry.authors.add(john, paul, george, ringo)  #在entry对象的多对多字段Author里添加多个对象

3.查询:

  查询主要是模拟的是SQL语句中的Select组合,查询集合相当于Select,过滤器相当于where和limit的限制语句;查询集主要是通过模型的objects管理器获得,表格上的操作,举例如下:

 1 >>> all_entries = Entry.objects.all() 

  查询集上的方法有:filter、exclude、get、all,并且查询集是惰性计算的。可以通过查询集合上的切片操作限定查询集合内的条目,类似与limit offset 语句,举例如下:

 1 >>> Entry.objects.all()[:10:2] #通过指定step查询集会进行计算,而其他的索引和切片操作只是产生新的查询集,并不计算 

  查询集上的字段查询部分:包括字段和查询type两部分,基本形式是field__lookuptype=value,举例如下:

 1 >>> Entry.objects.filter(pub_date__lte='2006-01-01') 

  lookuptype函数有cotains、startswith、endswith等等

  跨关系查询:很重要,前面的字段查询部分至少字段部分是前面模型的字段,而跨关系的查询字段部分引用的是另一个对象的属性,

 1 >>>Blog.objects.filter(entry__authors__isnull=False,entry__authors__name__isnull=True) 2 #引用了Entry模型中的authors属性 3  

  跨越多个值的查询,比较一下俩个:

 1 Blog.objects.filter(entry__headline__contains='Lennon', 2 entry__pub_date__year=2008) 

 1 Blog.objects.filter(entry__headline__contains='Lennon').filter( 2 entry__pub_date__year=2008) 

前者的entry条目必须同时符合Lennon和2008条件,重点是条目部分的and;而后者重点是Blog部分,如果这个Blog至少拥有一个lennon条目和一个2008条目或者拥有一个条目中同时包含lennon和2008的部分就算满足条件。

但是下面的exclude语句稍微有点不同:

1 Blog.objects.exclude(
2     entry__headline__contains='Lennon',
3     entry__pub_date__year=2008,
4 )

它会排除headline_lennon的blogs和pub_date=2008的blogs,要达到排除同时满足headline 和 pub_date__year条目的blog,可以使用如下的语句:

1 Blog.objects.exclude(
2     entry=Entry.objects.filter(
3         headline__contains='Lennon',
4         pub_date__year=2008,
5     ),
6 )

    F表达式:比较同一模型中的不同字段的表达式子,举例如下

 1 >>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks')) 

 1 >>> Entry.objects.filter(authors__name=F('blog__name')) #author的名字和blog名字相同 

 

posted on 2015-10-20 22:32  chzb  阅读(261)  评论(0)    收藏  举报

导航