Django Doc:Making queries
來自專欄 Python
摘自Making queries | Django documentation | Django
Once you』ve created yourdata models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects.
Creating objects
To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table.
To create an object, instantiate it using keyword arguments to the model class, then call save()
to save it to the database.
Throughout this guide (and in the reference), we』ll refer to the following models, which comprise a Weblog application:
from django.db import modelsclass Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.nameclass Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.nameclass Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline
Assuming models live in a filemysite/blog/models.py
, here』s an example:
>>> from blog.models import Blog>>> b = Blog(name=Beatles Blog, tagline=All the latest Beatles news.)>>> b.save()
This performs an INSERT
SQL statement behind the scenes. Django doesn』t hit the database until you explicitly call save()
.
The save()
method has no return value.
Saving changes to objects
To save changes to an object that』s already in the database, use save()
.
This performs anUPDATE
SQL statement behind the scenes
Retrieving objects
To retrieve objects from your database, construct a QuerySet
via a Manager
on your model class.
A QuerySet
represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet
equates to a SELECT
statement, and a filter is a limiting clause such as WHERE
or LIMIT
.
You get a QuerySet
by using your model』s Manager
. Each model has at least one Manager
, and it』s calledobjects
by default.
Managers
are accessible only via model classes, rather than from model instances, to enforce a separation between 「table-level」 operations and 「record-level」 operations.
Retrieving all objects
The simplest way to retrieve objects from a table is to get all of them. To do this, use the all()
method on aManager
:
>>> all_entries = Entry.objects.all()
Retrieving specific objects with filters
To create a subset of the complete set of objects, you refine the initial QuerySet
, adding filter conditions. The two most common ways to refine a QuerySet
are:
filter(**kwargs)
Returns a newQuerySet
containing objects that match the given lookup parameters.
exclude(**kwargs)
Returns a newQuerySet
containing objects that do not match the given lookup parameters.
The lookup parameters (**kwargs
in the above function definitions) should be in the format described in Field lookups below.
For example, to get a QuerySet
of blog entries from the year 2006, use filter()
like so:
Entry.objects.filter(pub_date__year=2006)
With the default manager class, it is the same as:
Entry.objects.all().filter(pub_date__year=2006)
Chaining filters
The result of refining a QuerySet
is itself a QuerySet
, so it』s possible to chain refinements together.
Each time you refine aQuerySet
, you get a brand-newQuerySet
that is in no way bound to the previousQuerySet
. Each refinement creates a separate and distinctQuerySet
that can be stored, used and reused.
QuerySets
are lazy – the act of creating aQuerySet
doesn』t involve any database activity. You can stack filters together all day long, and Django won』t actually run the query until theQuerySet
is evaluated.
>>> q = Entry.objects.filter(headline__startswith="What")>>> q = q.filter(pub_date__lte=datetime.date.today())>>> q = q.exclude(body_text__icontains="food")>>> print(q)
Though this looks like three database hits, in fact it hits the database only once, at the last line (print(q)
)
Retrieving a single object with get()
filter()
will always give you a QuerySet
, even if only a single object matches the query - in this case, it will be a QuerySet
containing a single element.
If you know there is only one object that matches your query, you can use the get()
method on a Manager
which returns the object directly:
>>> one_entry = Entry.objects.get(pk=1)
You can use any query expression with get()
, just like with filter()
- again, see Field lookups below.
Note that there is a difference between using get()
, and using filter()
with a slice of [0]
. If there are no results that match the query, get()
will raise a DoesNotExist
exception. This exception is an attribute of the model class that the query is being performed on - so in the code above, if there is no Entry
object with a primary key of 1, Django will raise Entry.DoesNotExist
.
Similarly, Django will complain if more than one item matches the get()
query. In this case, it will raiseMultipleObjectsReturned
, which again is an attribute of the model class itself.
to be continued.
推薦閱讀:
※世界上最受中國人歡迎的電影,你看過幾個?
※我用Hexo寫博客
※如何用Python和深度神經網路識別圖像?
※Python到底有多慢?
※Python多線程threading—圖片下載