博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django:model类的objects属性
阅读量:4053 次
发布时间:2019-05-25

本文共 5509 字,大约阅读时间需要 18 分钟。

A model class's objects attribute is an instance of django.db.models.manager.Manager. A manager has the following methods, all of which return a QuerySet instance.

  • all() -- Returns a QuerySet of all objects in the database. This is like the old get_list(). Takes no arguments.
  • filter(**kwargs) -- Returns a QuerySet, filtered by the given keyword arguments. Lookup arguments are in the same style as previously, e.g. pubdate__year=2005, except you can leave off __exact as a convenience. For example, name='John' and name__exact='John' are equivalent. Note that for lookups between applications you can't omit __exact.
  • exclude(**kwargs) is the same as filter(), but returns objects where the given arguments are not true.
  • order_by(*fieldnames) -- Returns a QuerySet
  • count() -- Returns the count of all objects in the database.
  • dates(field_name, kind) -- Like the old get_FIELD_list() for date fields. For example, old-school get_pubdate_list('year') is now dates('pubdate', 'year').
  • delete() -- Deletes all objects.
  • distinct() -- Returns a QuerySet with DISTINCT set.
  • extra(select=None, where=None, params=None, tables=None) -- Sets the select, where, params and tables arguments, which are in the same format as before.
  • get(**kwargs) -- Like the old get_object(). Returns an object or raises DoesNotExist on error.
  • in_bulk(id_list) -- Like the old get_in_bulk().
  • iterator() -- Returns a generator that iterators over results.
  • select_related() -- Returns a QuerySet with the "select related" option (which acts the same as before) set.
  • values(*fieldnames) -- Like the old get_values().

Each QuerySet has the following methods, which return a clone of the query set with the appropriate changes made:

  • filter(**kwargs)
  • order_by(*fieldnames)
  • iterator()
  • count()
  • get(**kwargs)
  • delete()
  • filter(**kwargs)
  • select_related()
  • order_by(*fieldnames)
  • distinct()
  • extra(select=None, where=None, params=None, tables=None)

Here are some examples, which use the following models:

class Reporter(models.Model):    fname = models.CharField(maxlength=30)    lname = models.CharField(maxlength=30)class Site(models.Model):    name = models.CharField(maxlength=20)class Article(models.Model):    headline = models.CharField(maxlength=50)    reporter = models.ForeignKey(Reporter)    pub_date = models.DateField()    sites = models.ManyToManyField(Site)
Old syntax New syntax
reporters.get_list() Reporter.objects.all()
reporters.get_list(fname__exact='John') Reporter.objects.filter(fname='John')
reporters.get_list(order_by=('-lname', 'fname')) Reporter.objects.order_by('-lname', 'fname')
reporters.get_list(fname__exact='John', order_by=('lname',)) Reporter.objects.filter(fname='John').order_by('lname')
reporters.get_object(pk=3) Reporter.objects.get(pk=3)
reporters.get_object(complex=(Q(...)|Q(...))) Reporter.objects.get(Q(...)|Q(...))
reporters.get_object(fname__contains='John') Reporter.objects.get(fname__contains='John')
reporters.get_list(fname__ne='John') Reporter.objects.exclude(fname='John') (note that ne is no longer a valid lookup type)
(not previously possible) Reporter.objects.exclude(fname__contains='n')
reporters.get_list(distinct=True) Reporter.objects.distinct()
reporters.get_list(offset=10, limit=5) Reporter.objects.all()[10:15]
reporters.get_values() Reporter.objects.values()
reporters.get_in_bulk([1, 2]) Reporter.objects.in_bulk([1, 2])
reporters.get_in_bulk([1, 2], fname__exact='John') Reporter.objects.filter(fname='John').in_bulk([1, 2])
Date lookup  
articles.get_pub_date_list('year') Article.objects.dates('pub_date', 'year')
Latest-object lookup  
articles.get_latest() (required get_latest_by in model) Article.objects.latest() (with get_latest_by in model)
(Not previously possible) Article.objects.latest('pub_date') # Latest by pub_date (overrides get_latest_by field in model)
Many-to-one related lookup  
article_obj.reporter_id article_obj.reporter.id
article_obj.get_reporter() article_obj.reporter
reporter_obj.get_article_list() reporter_obj.article_set.all()
reporter_obj.get_article_list(headline__exact='Hello') reporter_obj.article_set.filter(headline='Hello')
reporter_obj.get_article_count() reporter_obj.article_set.count()
reporter_obj.add_article(headline='Foo') reporter_obj.article_set.create(headline='Foo')
(Alternate syntax) reporter_obj.article_set.add(article_obj)
("values" lookup, etc., not previously possible) reporter_obj.article_set.values()
Many-to-many related lookup  
article_obj.get_site_list() article_obj.sites.all()
article_obj.set_sites([s1.id, s2.id]) article_obj.sites.clear(); article_obj.sites.add(s1); article_obj.sites.add(s2)
article_obj.set_sites([s1.id]) # deletion article_obj.sites.remove(s2)
site_obj.get_article_list() site_obj.article_set.all()

Note that related-object lookup uses the default manager of the related object, which means the API for accessing related objects is completely consistent with the API for accessing objects via a manager.

Also note that managers can't be accessed from instances:

p = Person.objects.get(pk=1)p.objects.all() # Raises AttributeError

Override default manager name ('objects')

If a model already has an objects attribute, you'll need to specify an alternate name for the objects manager.

class Person(models.Model):    first_name = models.CharField(maxlength=30)    last_name = models.CharField(maxlength=30)    objects = models.TextField()    people = models.Manager()p = Person(first_name='Mary', last_name='Jones', objects='Hello there.')p.save()p.objects == 'Hello there.'Person.people.all()

原文链接:

转载地址:http://bkxci.baihongyu.com/

你可能感兴趣的文章
函数模版类模版和偏特化泛化的总结
查看>>
VMware Workstation Pro虚拟机不可用解决方法
查看>>
最简单的使用redis自带程序实现c程序远程访问redis服务
查看>>
redis学习总结-- 内部数据 字符串 链表 字典 跳跃表
查看>>
iOS 对象序列化与反序列化
查看>>
iOS 序列化与反序列化(runtime) 01
查看>>
iOS AFN 3.0版本前后区别 01
查看>>
iOS ASI和AFN有什么区别
查看>>
iOS QQ侧滑菜单(高仿)
查看>>
iOS 扫一扫功能开发
查看>>
iOS app之间的跳转以及传参数
查看>>
iOS __block和__weak的区别
查看>>
Android(三)数据存储之XML解析技术
查看>>
Spring JTA应用之JOTM配置
查看>>
spring JdbcTemplate 的若干问题
查看>>
Servlet和JSP的线程安全问题
查看>>
GBK编码下jQuery Ajax中文乱码终极暴力解决方案
查看>>
Oracle 物化视图
查看>>
PHP那点小事--三元运算符
查看>>
解决国内NPM安装依赖速度慢问题
查看>>