Django:model类的objects属性

By 肖奈
2017-11-02
3552 read

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 selectwhereparamsand 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 syntaxNew 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_idarticle_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]) # deletionarticle_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 theobjects 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()


python 字符串的操作
python url

Comments

暂无评论,还不快来坐沙发...

Leave a Reply