首页 > 代码库 > django models Making queries

django models Making queries

这是后面要用到的类

class Blog(models.Model):    name = models.CharField(max_length=100)    tagline = models.TextField()    def __unicode__(self):        return self.nameclass Author(models.Model):    name = models.CharField(max_length=50)    email = models.EmailField()    def __unicode__(self):        return self.nameclass Entry(models.Model):    blog = models.ForeignKey(Blog)    headline = models.CharField(max_length=255)    body_text = models.TextField()    pub_date = models.DateTimeField()    mod_date = models.DateTimeField()    authors = models.ManyToManyField(Author)    n_comments = models.IntegerField()    n_pingbacks = models.IntegerField()    rating = models.IntegerField()    def __unicode__(self):        return self.headline

 

Creating objects

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

 

Saving ForeignKey and ManyToManyField fields

>>> from blog.models import Entry>>> entry = Entry.objects.get(pk=1)>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")>>> entry.blog = cheese_blog>>> entry.save()>>> from blog.models import Author>>> joe = Author.objects.create(name="Joe")>>> entry.authors.add(joe)>>> john = Author.objects.create(name="John")>>> paul = Author.objects.create(name="Paul")>>> george = Author.objects.create(name="George")>>> ringo = Author.objects.create(name="Ringo")>>> entry.authors.add(john, paul, george, ringo)

 

Retrieving objects

>>> Blog.objects<django.db.models.manager.Manager object at ...>>>> b = Blog(name=Foo, tagline=Bar)>>> b.objectsTraceback:    ...AttributeError: "Manager isn‘t accessible via Blog instances."

 

Retrieving all objects

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

 

filter(**kwargs)

Returns a new QuerySet containing objects that match the given lookup parameters.

exclude(**kwargs)

Returns a new QuerySet containing objects that do not match the given lookup parameters.

Entry.objects.filter(pub_date__year=2006)

Chaining filters

>>> Entry.objects.filter(...     headline__startswith=What... ).exclude(...     pub_date__gte=datetime.now()... ).filter(...     pub_date__gte=datetime(2005, 1, 1)... )

 

get,get 方法会返回符合条件的那个元素,当没有符合筛选条件的元素是get方法会抛出一个 DoesNotExist的异常,所以要慎用

>>> one_entry = Entry.objects.get(pk=1)

 

Field lookups

筛选属性的时候的一些限制条件,基本格式是 field__lookuptype=value,注意是双下划线,下面是lookuptype

exact:Exact match,准确匹配,可以匹配到null(None) iexact: 不区分大小写的准确匹配

contains:包含                                                        icontains:不区分大小写的包含

in:在(一个筛选的列表)里面

gt :Greater than                                                    gte:Greater than or equal to.

lt:Less than.                                                          lte:Less than or equal to.

startswith,istartswith,endswith,iendswith

range:pub_date__range=(start_date, end_date))

year,month,day,weekday,

regex:正则表达式匹配,iregex,不区分大小写的

Aggregation functions

聚合函数,针对查询集合的一些操作

Avg:计算平均值,返回值类型float

Count:计算集合的元素个数,返回值类型int

Max,Min,Sum

p

django models Making queries