Django:model类的objects属性

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 selectwhereparams 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)
posted @ 2022-05-12 21:16  星辰大海日夜兼程  阅读(222)  评论(0编辑  收藏  举报