Membuat query¶
Once you’ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects. This document explains how to use this API. Refer to the data model reference for full details of all the various model lookup options.
Throughout this guide (and in the reference), we’ll refer to the following models, which comprise a Weblog application:
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self): # __unicode__ on Python 2
return self.name
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
def __str__(self): # __unicode__ on Python 2
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog)
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): # __unicode__ on Python 2
return self.headline
Membuat obyek¶
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.
Menganggap model tinggal di berkas mysite/blog/models.py
, ini adalah sebuah contoh:
>>> 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()
.
Cara save()
tidak mempunyai nilai kembalian.
Menyimpan perubahan ke obyek¶
Untuk menyimpan perubahan ke sebuah obyek yang sudah ada di basisdata gunakan save()
.
Given a Blog
instance b5
that has already been saved to the database,
this example changes its name and updates its record in the database:
>>> b5.name = 'New name'
>>> b5.save()
This performs an UPDATE
SQL statement behind the scenes. Django doesn’t hit
the database until you explicitly call save()
.
Menyimpan bidang ForeignKey
dan ManyToManyField
¶
Updating a ForeignKey
field works exactly the same
way as saving a normal field – simply assign an object of the right type to
the field in question. This example updates the blog
attribute of an
Entry
instance entry
, assuming appropriate instances of Entry
and
Blog
are already saved to the database (so we can retrieve them below):
>>> 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()
Updating a ManyToManyField
works a little
differently – use the
add()
method on the field
to add a record to the relation. This example adds the Author
instance
joe
to the entry
object:
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
To add multiple records to a ManyToManyField
in one
go, include multiple arguments in the call to
add()
, like this:
>>> 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)
Django akan mengeluh jika anda mencoba memberikan atau menambahkan sebuah obyek dari jenis salah.
Mengambil obyek¶
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 called
objects
by default. Access it directly via the
model class, like so:
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
Traceback:
...
AttributeError: "Manager isn't accessible via Blog instances."
Catatan
Managers
are accessible only via model classes, rather than from model
instances, to enforce a separation between “table-level” operations and
“record-level” operations.
The Manager
is the main source of QuerySets
for
a model. For example, Blog.objects.all()
returns a
QuerySet
that contains all Blog
objects in
the database.
Mengambil semua obyek¶
The simplest way to retrieve objects from a table is to get all of them. To do
this, use the all()
method on a
Manager
:
>>> all_entries = Entry.objects.all()
The all()
method returns a
QuerySet
of all the objects in the database.
Mengambil obyek spesifik dengan menyaring¶
The QuerySet
returned by
all()
describes all objects in the
database table. Usually, though, you’ll need to select only a subset of the
complete set of objects.
To create such a subset, you refine the initial
QuerySet
, adding filter conditions. The two
most common ways to refine a QuerySet
are:
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.
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. For example:
>>> Entry.objects.filter(
... headline__startswith='What'
... ).exclude(
... pub_date__gte=datetime.date.today()
... ).filter(
... pub_date__gte=datetime(2005, 1, 30)
... )
This takes the initial QuerySet
of all entries
in the database, adds a filter, then an exclusion, then another filter. The
final result is a QuerySet
containing all
entries with a headline that starts with “What”, that were published between
January 30, 2005, and the current day.
Filtered QuerySet
s are unique¶
Each time you refine a QuerySet
, you get a
brand-new QuerySet
that is in no way bound to
the previous QuerySet
. Each refinement creates
a separate and distinct QuerySet
that can be
stored, used and reused.
Contoh:
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())
These three QuerySets
are separate. The first is a base
QuerySet
containing all entries that contain a
headline starting with “What”. The second is a subset of the first, with an
additional criteria that excludes records whose pub_date
is today or in the
future. The third is a subset of the first, with an additional criteria that
selects only the records whose pub_date
is today or in the future. The
initial QuerySet
(q1
) is unaffected by the
refinement process.
QuerySet
s are lazy¶
QuerySets
are lazy – the act of creating a
QuerySet
doesn’t involve any database
activity. You can stack filters together all day long, and Django won’t
actually run the query until the QuerySet
is
evaluated. Take a look at this example:
>>> 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)
). In general, the results of a
QuerySet
aren’t fetched from the database
until you “ask” for them. When you do, the
QuerySet
is evaluated by accessing the
database. For more details on exactly when evaluation takes place, see
When QuerySets are evaluated.
Mengambil obyek tunggal dengan 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 raise
MultipleObjectsReturned
, which again is an
attribute of the model class itself.
Cara QuerySet
lain¶
Most of the time you’ll use all()
,
get()
,
filter()
and
exclude()
when you need to look up
objects from the database. However, that’s far from all there is; see the
QuerySet API Reference for a complete list of all the
various QuerySet
methods.
Membatasi QuerySet
¶
Use a subset of Python’s array-slicing syntax to limit your
QuerySet
to a certain number of results. This
is the equivalent of SQL’s LIMIT
and OFFSET
clauses.
Sebagai contoh, ini mengembalikan 5 obyek pertama (LIMIT 5
):
>>> Entry.objects.all()[:5]
Ini mengembalikan enam dari 10 obyek (OFFSET 5 LIMIT 5
):
>>> Entry.objects.all()[5:10]
Negative indexing (i.e. Entry.objects.all()[-1]
) is not supported.
Generally, slicing a QuerySet
returns a new
QuerySet
– it doesn’t evaluate the query. An
exception is if you use the “step” parameter of Python slice syntax. For
example, this would actually execute the query in order to return a list of
every second object of the first 10:
>>> Entry.objects.all()[:10:2]
To retrieve a single object rather than a list
(e.g. SELECT foo FROM bar LIMIT 1
), use a simple index instead of a
slice. For example, this returns the first Entry
in the database, after
ordering entries alphabetically by headline:
>>> Entry.objects.order_by('headline')[0]
This is roughly equivalent to:
>>> Entry.objects.order_by('headline')[0:1].get()
Note, however, that the first of these will raise IndexError
while the
second will raise DoesNotExist
if no objects match the given criteria. See
get()
for more details.
Field lookups¶
Field lookups are how you specify the meat of an SQL WHERE
clause. They’re
specified as keyword arguments to the QuerySet
methods filter()
,
exclude()
and
get()
.
Basic lookups keyword arguments take the form field__lookuptype=value
.
(That’s a double-underscore). For example:
>>> Entry.objects.filter(pub_date__lte='2006-01-01')
terjemahan (kurang lebih) ke dalam SQL berikut:
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
Bagaimana ini mungkin
Python has the ability to define functions that accept arbitrary name-value arguments whose names and values are evaluated at runtime. For more information, see Keyword Arguments in the official Python tutorial.
The field specified in a lookup has to be the name of a model field. There’s
one exception though, in case of a ForeignKey
you
can specify the field name suffixed with _id
. In this case, the value
parameter is expected to contain the raw value of the foreign model’s primary
key. For example:
>>> Entry.objects.filter(blog_id=4)
If you pass an invalid keyword argument, a lookup function will raise
TypeError
.
The database API supports about two dozen lookup types; a complete reference can be found in the field lookup reference. To give you a taste of what’s available, here’s some of the more common lookups you’ll probably use:
exact
Sebuah pencocokan “tepat”. Sebagai contoh:
>>> Entry.objects.get(headline__exact="Cat bites dog")
Akan membangkitkan SQL bersama baris ini:
SELECT ... WHERE headline = 'Cat bites dog';
If you don’t provide a lookup type – that is, if your keyword argument doesn’t contain a double underscore – the lookup type is assumed to be
exact
.Sebagai contoh, dua pernyataan berikut adalah setara:
>>> Blog.objects.get(id__exact=14) # Explicit form >>> Blog.objects.get(id=14) # __exact is implied
This is for convenience, because
exact
lookups are the common case.iexact
A case-insensitive match. So, the query:
>>> Blog.objects.get(name__iexact="beatles blog")
Would match a
Blog
titled"Beatles Blog"
,"beatles blog"
, or even"BeAtlES blOG"
.contains
Case-sensitive containment test. For example:
Entry.objects.get(headline__contains='Lennon')
Kurang lebih menterjemahkan ke SQL ini:
SELECT ... WHERE headline LIKE '%Lennon%';
Note this will match the headline
'Today Lennon honored'
but not'today lennon honored'
.There’s also a case-insensitive version,
icontains
.startswith
,endswith
- Starts-with and ends-with search, respectively. There are also
case-insensitive versions called
istartswith
andiendswith
.
Again, this only scratches the surface. A complete reference can be found in the field lookup reference.
Lookups that span relationships¶
Django offers a powerful and intuitive way to “follow” relationships in
lookups, taking care of the SQL JOIN
s for you automatically, behind the
scenes. To span a relationship, just use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.
This example retrieves all Entry
objects with a Blog
whose name
is 'Beatles Blog'
:
>>> Entry.objects.filter(blog__name='Beatles Blog')
Jangkauan ini dapat sedalam anda sukai.
Itu bekerja kebelakang, juga. Untuk mengacu hubungan “reverse”, cukup gunakan nama huruf kecil dari model.
This example retrieves all Blog
objects which have at least one Entry
whose headline
contains 'Lennon'
:
>>> Blog.objects.filter(entry__headline__contains='Lennon')
If you are filtering across multiple relationships and one of the intermediate
models doesn’t have a value that meets the filter condition, Django will treat
it as if there is an empty (all values are NULL
), but valid, object there.
All this means is that no error will be raised. For example, in this filter:
Blog.objects.filter(entry__authors__name='Lennon')
(if there was a related Author
model), if there was no author
associated with an entry, it would be treated as if there was also no name
attached, rather than raising an error because of the missing author
.
Usually this is exactly what you want to have happen. The only case where it
might be confusing is if you are using isnull
. Thus:
Blog.objects.filter(entry__authors__name__isnull=True)
will return Blog
objects that have an empty name
on the author
and
also those which have an empty author
on the entry
. If you don’t want
those latter objects, you could write:
Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
Spanning multi-valued relationships¶
Ketika anda menyaring sebuah obyek berdasarkan pada sebuah ManyToManyField
atau membalikkan ForeignKey
, ada dua perbedaan urutan dari penyaringan anda mungkin tertarik. Pertimbangkan hubungan Blog
/Entry
(Blog
pada Entry
adalah hubungan one-to-many). Kami mungkin tertarik dalam menemukan blog yang memiliki sebuah masukan yang mempunyai kedua “Lennon” dalam judul dan telah diterbitkan di 2008. Atau kami mungkin ingin menemukan blog yang mempunyai sebuah masukan dengan “Lennon” dalam judul sama halnya sebuah masukan yang telah diterbitkan di 2008. Sejak ada banyak masukan terkait dengan Blog
tunggal, kedua dari permintaan ini adalah memungkinkan dan masuk akal dalam beberapa keadaan
The same type of situation arises with a
ManyToManyField
. For example, if an Entry
has a
ManyToManyField
called tags
, we might want to
find entries linked to tags called “music” and “bands” or we might want an
entry that contains a tag with a name of “music” and a status of “public”.
To handle both of these situations, Django has a consistent way of processing
filter()
calls. Everything inside a
single filter()
call is applied
simultaneously to filter out items matching all those requirements. Successive
filter()
calls further restrict the set
of objects, but for multi-valued relations, they apply to any object linked to
the primary model, not necessarily those objects that were selected by an
earlier filter()
call.
That may sound a bit confusing, so hopefully an example will clarify. To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write:
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
To select all blogs that contain an entry with “Lennon” in the headline as well as an entry that was published in 2008, we would write:
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
Suppose there is only one blog that had both entries containing “Lennon” and entries from 2008, but that none of the entries from 2008 contained “Lennon”. The first query would not return any blogs, but the second query would return that one blog.
In the second example, the first filter restricts the queryset to all those
blogs linked to entries with “Lennon” in the headline. The second filter
restricts the set of blogs further to those that are also linked to entries
that were published in 2008. The entries selected by the second filter may or
may not be the same as the entries in the first filter. We are filtering the
Blog
items with each filter statement, not the Entry
items.
Catatan
The behavior of filter()
for queries
that span multi-value relationships, as described above, is not implemented
equivalently for exclude()
. Instead,
the conditions in a single exclude()
call will not necessarily refer to the same item.
For example, the following query would exclude blogs that contain both entries with “Lennon” in the headline and entries published in 2008:
Blog.objects.exclude(
entry__headline__contains='Lennon',
entry__pub_date__year=2008,
)
However, unlike the behavior when using
filter()
, this will not limit blogs
based on entries that satisfy both conditions. In order to do that, i.e.
to select all blogs that do not contain entries published with “Lennon”
that were published in 2008, you need to make two queries:
Blog.objects.exclude(
entry__in=Entry.objects.filter(
headline__contains='Lennon',
pub_date__year=2008,
),
)
Filters can reference fields on the model¶
In the examples given so far, we have constructed filters that compare the value of a model field with a constant. But what if you want to compare the value of a model field with another field on the same model?
Django provides F expressions
to allow such
comparisons. Instances of F()
act as a reference to a model field within a
query. These references can then be used in query filters to compare the values
of two different fields on the same model instance.
For example, to find a list of all blog entries that have had more comments
than pingbacks, we construct an F()
object to reference the pingback count,
and use that F()
object in the query:
>>> from django.db.models import F
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
Django supports the use of addition, subtraction, multiplication,
division, modulo, and power arithmetic with F()
objects, both with constants
and with other F()
objects. To find all the blog entries with more than
twice as many comments as pingbacks, we modify the query:
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
To find all the entries where the rating of the entry is less than the sum of the pingback count and comment count, we would issue the query:
>>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
You can also use the double underscore notation to span relationships in
an F()
object. An F()
object with a double underscore will introduce
any joins needed to access the related object. For example, to retrieve all
the entries where the author’s name is the same as the blog name, we could
issue the query:
>>> Entry.objects.filter(authors__name=F('blog__name'))
For date and date/time fields, you can add or subtract a
timedelta
object. The following would return all entries
that were modified more than 3 days after they were published:
>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
The F()
objects support bitwise operations by .bitand()
and
.bitor()
, for example:
>>> F('somefield').bitand(16)
The pk
lookup shortcut¶
Untuk kemudahan, Django menyediakan jalan pintas pencarian pk
, yang berdiri untuk “primary key”.
Dalam contoh model Blog
, primary key adalah bidang id
, jadi pernyataan ini adalah setara:
>>> Blog.objects.get(id__exact=14) # Explicit form
>>> Blog.objects.get(id=14) # __exact is implied
>>> Blog.objects.get(pk=14) # pk implies id__exact
Penggunaan pk
tidak terbatas pada permintaan __exact
– apapun istilah permintaan dapat dipadukan dengan pk
untuk melakukan sebuah permintaan pada primary key pada model:
# Get blogs entries with id 1, 4 and 7
>>> Blog.objects.filter(pk__in=[1,4,7])
# Get all blog entries with id > 14
>>> Blog.objects.filter(pk__gt=14)
Pencarian pk
juga bekerja liintas join. Sebagai contoh, tiga pernyataan ini adalah setara:
>>> Entry.objects.filter(blog__id__exact=3) # Explicit form
>>> Entry.objects.filter(blog__id=3) # __exact is implied
>>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact
Meloloskan tanda persen dan garis bawah dalam pernyataan LIKE
¶
The field lookups that equate to LIKE
SQL statements (iexact
,
contains
, icontains
, startswith
, istartswith
, endswith
and iendswith
) will automatically escape the two special characters used in
LIKE
statements – the percent sign and the underscore. (In a LIKE
statement, the percent sign signifies a multiple-character wildcard and the
underscore signifies a single-character wildcard.)
Ini berarti hal-hal harus bekerja secara intuitif, jadi abstraksi tidak bocor. Sebagai contoh, untuk mengambil semua masukan yang mengandung tanda persen, cukup gunakan tanda persen sebagai katakter lain:
>>> Entry.objects.filter(headline__contains='%')
Django menangani dari pengutipan untuk anda; menghasilkan SQL akan mencari sesuatu seperti ini:
SELECT ... WHERE headline LIKE '%\%%';
Sama seperti garis bawah. Kedua tanda persen dan garis bawag ditangani untuk anda secara transparan.
Caching and QuerySet
s¶
Setiap QuerySet
mengandung sebuah tembolok untuk meminimalkan akses basisdata. Pahami bagaimana dia bekerja akan mengizinkan anda menulis kode paling efisien.
In a newly created QuerySet
, the cache is
empty. The first time a QuerySet
is evaluated
– and, hence, a database query happens – Django saves the query results in
the QuerySet
’s cache and returns the results
that have been explicitly requested (e.g., the next element, if the
QuerySet
is being iterated over). Subsequent
evaluations of the QuerySet
reuse the cached
results.
Keep this caching behavior in mind, because it may bite you if you don’t use
your QuerySet
s correctly. For example, the
following will create two QuerySet
s, evaluate
them, and throw them away:
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
That means the same database query will be executed twice, effectively doubling
your database load. Also, there’s a possibility the two lists may not include
the same database records, because an Entry
may have been added or deleted
in the split second between the two requests.
Untuk menghindari masalah ini, cukup simpan QuerySet
dan gunakan kembali
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset]) # Evaluate the query set.
>>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
When QuerySet
s are not cached¶
Querysets do not always cache their results. When evaluating only part of the queryset, the cache is checked, but if it is not populated then the items returned by the subsequent query are not cached. Specifically, this means that limiting the queryset using an array slice or an index will not populate the cache.
Sebagi contoh, secara berulang mendapatkan indeks tertentu di queryset obyek akan meminta basisdata setiap waktu:
>>> queryset = Entry.objects.all()
>>> print(queryset[5]) # Queries the database
>>> print(queryset[5]) # Queries the database again
Bagaimanapun, jika keseluruhan queryset sudah dinilai, tembolok akan diperiksa sebagai gantinya:
>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset] # Queries the database
>>> print(queryset[5]) # Uses cache
>>> print(queryset[5]) # Uses cache
Ini adalah beberapa contoh dari tindakan lain yang akan menghasilkan keseluruhan queryset yang sedang dinilai dan karena itu dikumpulkan tembolok:
>>> [entry for entry in queryset]
>>> bool(queryset)
>>> entry in queryset
>>> list(queryset)
Catatan
Mencetak sederhana queryset tidak akan mengumpulkan tembolok. Ini dikarenakan panggilan pada __repr__()
hanya mengembalikan potongan dari keseluruhan queryset.
Pencarian rumit dengan obyek Q
¶
Keyword argument queries – in filter()
,
etc. – are “AND”ed together. If you need to execute more complex queries (for
example, queries with OR
statements), you can use Q objects
.
A Q object
(django.db.models.Q
) is an object
used to encapsulate a collection of keyword arguments. These keyword arguments
are specified as in “Field lookups” above.
For example, this Q
object encapsulates a single LIKE
query:
from django.db.models import Q
Q(question__startswith='What')
Q
objects can be combined using the &
and |
operators. When an
operator is used on two Q
objects, it yields a new Q
object.
Sebagai contoh, pernyataan ini menghasilkan obyek Q
tunggal yang mewakili “OR” atau dua permintaan "question__startswith"
Q(question__startswith='Who') | Q(question__startswith='What')
Ini sama pada klausa SQL WHERE
berikut:
WHERE question LIKE 'Who%' OR question LIKE 'What%'
Anda dapat menyusun pernyataan dari kerumitan yang berubah-ubah dengan memadukan obyek Q
dengan penghubung &
and |
dan gunakan pengelompokan yang disipkan. Juga, obyek Q
dapat ditugaskan menggunakan penghubung ~
, mengizinkan perpaduan pencarian yang memadukan kedua permintaan normal dan meniadakan permintaan (NOT
):
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
Setiap fungsi pencarian yang mengambil argumen-kata kunci (sebagai contoh filter()
, exclude()
, get()
) dapat juga melewatkan satu atau lebih obyek Q
sebagai argumen (tidak-dinamai) kedudukan. Jika anda menyediakan banyak argumen obyek Q
pada fungsi pencarian, argumen akan di “AND”kan bersama-sama. Sebagai contoh:
Poll.objects.get(
Q(question__startswith='Who'),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
... kurang lebih menterjemahkan ke dalam SQL:
SELECT * from polls WHERE question LIKE 'Who%'
AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
Fungsi pencarian dapat mencampurkan penggunaan obyek Q
dan argumen kata kunci. Semua argumen disediakan untuk fungsi pencarian (menjadi mereka argumen kata kunci atau obyek Q
) di “AND”kan bersama-sama. Bagaimanapun, jika obyek Q
disediakan, dia harus mendahului pengertian dari argumen kata kunci apapun. Sebagai contoh:
Poll.objects.get(
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
question__startswith='Who',
)
... akan menjadi permintaan sah, sama pada contoh sebelumnya; tetapi:
# INVALID QUERY
Poll.objects.get(
question__startswith='Who',
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
... tidak akan menjadi sah.
lihat juga
OR lookups examples dalam satuan percobaan Django menampilkan beberapa kemungkinan penggunaan dari Q
.
Membandingkan obyek¶
Untuk membandingkan dua model instance, cukup gunakan penghubung perbandingan standar Python, tanda sama dengan ganda: ==
. Dibelakang layar, yang membandingkan nilai primary key dari dua model.
Menggunakan contoh Entry
diatas, dua pernyataan berikut adalah setara:
>>> some_entry == other_entry
>>> some_entry.id == other_entry.id
Jika sebuah primary key model tidak memanggil id
, tidak masalah. Perbandingan akan selalu menggunakan primary key, apapun itu memanggilnya. Sebagai contoh, jika sebuah primary key model dipanggil name
, dua pernyataan ini adalah setara:
>>> some_obj == other_obj
>>> some_obj.name == other_obj.name
menghapus obyek¶
Untuk menghapus metode, mudah, adalah bernama delete()
. Metode ini segera menghapus obyek dan mengembalikan sejumlah obyek yang dihapus dan sebuah kamus dengan sejumlah penghapusan per jenis obyek. Contoh:
>>> e.delete()
(1, {'weblog.Entry': 1})
Nilai kembalian menggambarkan angka dari obyek dihapus telah ditambahkan.
Anda dapat juga menghapus obyek dalam jumlah besar. Setiap QuerySet
mempunyai sebuah delete()
method, yang menghapus semua anggota dari QuerySet
tersebut.
Sebagai contoh, ini menghapus semua obyek Entry
dengan tahun pub-date
dari 2005:
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
Ingat bahwa ini akan, ketika memungkinkan, akan dijalankan murni dalam SQL, dan juga cara delete()
dari instance tidak akan perlu dipanggil selama pengolahan. Jika anda telah menyediakan cara delete()
disesuaikan pada sebuah kelas model dan ingin memastikan bahwa dia dipanggil, anda akan butuh “secara manual” menghapus instance dari model tersebut (sebagai contoh, dengan perulangan terhadap QuerySet
dan memanggil delete()
pada setiap obyek secara tersendiri) daripada menggunakan dalam jumlah besar cara delete()
dari sebuah QuerySet
.
Nilai kembalian menggambarkan angka dari obyek dihapus telah ditambahkan.
Ketika DJANGO menghapus sebuah obyek, secara awal dia meniru kebiasaan batasan SQL ON DELETE CASCADE
– dalam kata lain, obyek apapun yang mempunyai foreign key menunjuk pada obyek yang akan dihapus akan dihapus bersama dengannya. Sebagai contoh:
b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()
Kebiasaan turunan ini dapat di sesuaikan melalui argumen on_delete
ke ForeignKey
.
Catat bahwa delete()
adalah hanya cara QuerySet
yang tidak ditunjukkan pada Manager
itu sendiri. Ini adalah mekanisme aman untuk mencegah anda dari kecelakaan permintaan Entry.objects.delete()
, dan menghapus semua masukan. Jika anda ingin melakukan menghapus semua obyek, kemudian anda harus secara jelas meminta kumpulan permintaan lengkap:
Entry.objects.all().delete()
Menyalin instance model¶
Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields’ values copied. In the
simplest case, you can just set pk
to None
. Using our blog example:
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
blog.save() # blog.pk == 2
Hal-hal dapat lebih rumit jika anda menggunakan warisan. Pertimbangkan subkelas dari Blog
:
class ThemeBlog(Blog):
theme = models.CharField(max_length=200)
django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')
django_blog.save() # django_blog.pk == 3
Disebabkan oleh bagaimana warisan bekerja, anda harus menyetel kedua pk
dan id
menjadi None:
django_blog.pk = None
django_blog.id = None
django_blog.save() # django_blog.pk == 4
This process doesn’t copy relations that aren’t part of the model’s database
table. For example, Entry
has a ManyToManyField
to Author
. After
duplicating an entry, you must set the many-to-many relations for the new
entry:
entry = Entry.objects.all()[0] # some previous entry
old_authors = entry.authors.all()
entry.pk = None
entry.save()
entry.authors.set(old_authors)
For a OneToOneField
, you must duplicate the related object and assign it
to the new object’s field to avoid violating the one-to-one unique constraint.
For example, assuming entry
is already duplicated as above:
detail = EntryDetail.objects.all()[0]
detail.pk = None
detail.entry = entry
detail.save()
Memperbaharui banyak obyek sekaligus¶
Terkadang anda ingin menyetel sebuah bidang ke nilai tertentu untuk semua obyek dalam QuerySet
. Anda dapat melakukan ini dengan cara update()
. Sebagai contoh:
# Update all the headlines with pub_date in 2007.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
You can only set non-relation fields and ForeignKey
fields using this method. To update a non-relation field, provide the new value
as a constant. To update ForeignKey
fields, set the
new value to be the new model instance you want to point to. For example:
>>> b = Blog.objects.get(pk=1)
# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.all().update(blog=b)
The update()
method is applied instantly and returns the number of rows
matched by the query (which may not be equal to the number of rows updated if
some rows already have the new value). The only restriction on the
QuerySet
being updated is that it can only
access one database table: the model’s main table. You can filter based on
related fields, but you can only update columns in the model’s main
table. Example:
>>> b = Blog.objects.get(pk=1)
# Update all the headlines belonging to this Blog.
>>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')
Be aware that the update()
method is converted directly to an SQL
statement. It is a bulk operation for direct updates. It doesn’t run any
save()
methods on your models, or emit the
pre_save
or post_save
signals (which are a consequence of calling
save()
), or honor the
auto_now
field option.
If you want to save every item in a QuerySet
and make sure that the save()
method is called on
each instance, you don’t need any special function to handle that. Just loop
over them and call save()
:
for item in my_queryset:
item.save()
Calls to update can also use F expressions
to
update one field based on the value of another field in the model. This is
especially useful for incrementing counters based upon their current value. For
example, to increment the pingback count for every entry in the blog:
>>> Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
However, unlike F()
objects in filter and exclude clauses, you can’t
introduce joins when you use F()
objects in an update – you can only
reference fields local to the model being updated. If you attempt to introduce
a join with an F()
object, a FieldError
will be raised:
# This will raise a FieldError
>>> Entry.objects.update(headline=F('blog__name'))
Falling back to raw SQL¶
If you find yourself needing to write an SQL query that is too complex for Django’s database-mapper to handle, you can fall back on writing SQL by hand. Django has a couple of options for writing raw SQL queries; see Performing raw SQL queries.
Finally, it’s important to note that the Django database layer is merely an interface to your database. You can access your database via other tools, programming languages or database frameworks; there’s nothing Django-specific about your database.