Bidang-bidang model khusus PostgreSQLLink to this heading
Semua dari bidang ini tersedia dari modul django.contrib.postgres.fields.
ArrayFieldLink to this heading
- class ArrayField(base_field, size=None, **options)Link to this definition
Sebuah bidang untuk menyimpan daftar data. Kebanyakan jenis bidang dapat digunakan, anda cukup melewatkan instance bidang lain sebagai
base_field. Anda mungkin juga menentukan sebuahsize.ArrayFielddapat disarangkan untuk menyimpan larik dimensi-banyak.If you give the field a
default, ensure it's a callable such aslist(for an empty default) or a callable that returns a list (such as a function). Incorrectly usingdefault=[]creates a mutable default that is shared between all instances ofArrayField.- base_fieldLink to this definition
Ini adalah sebuah argumen diwajibkan.
Specifies the underlying data type and behavior for the array. It should be an instance of a subclass of
Field. For example, it could be anIntegerFieldor aCharField. Most field types are permitted, with the exception of those handling relational data (ForeignKey,OneToOneFieldandManyToManyField).Itu memungkinkan menyarang bidang-bidang larik - anda dapat menentukan sebuah instance dari
ArrayFieldsebagaibase_field. Sebagai contoh:from django.db import models from django.contrib.postgres.fields import ArrayField class ChessBoard(models.Model): board = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, )Transformation of values between the database and the model, validation of data and configuration, and serialization are all delegated to the underlying base field.
- sizeLink to this definition
Ini adalah sebuah argumen pilihan.
If passed, the array will have a maximum size as specified. This will be passed to the database, although PostgreSQL at present does not enforce the restriction.
Meminta ArrayFieldLink to this heading
There are a number of custom lookups and transforms for ArrayField.
We will use the following example model:
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Post(models.Model):
name = models.CharField(max_length=200)
tags = ArrayField(models.CharField(max_length=200), blank=True)
def __str__(self): # __unicode__ on Python 2
return self.name
containsLink to this heading
The contains lookup is overridden on ArrayField. The
returned objects will be those where the values passed are a subset of the
data. It uses the SQL operator @>. For example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
>>> Post.objects.filter(tags__contains=['thoughts'])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__contains=['django'])
<QuerySet [<Post: First post>, <Post: Third post>]>
>>> Post.objects.filter(tags__contains=['django', 'thoughts'])
<QuerySet [<Post: First post>]>
contained_byLink to this heading
This is the inverse of the contains lookup -
the objects returned will be those where the data is a subset of the values
passed. It uses the SQL operator <@. For example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
>>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
overlapLink to this heading
Returns objects where the data shares any results with the values passed. Uses
the SQL operator &&. For example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
>>> Post.objects.filter(tags__overlap=['thoughts'])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
lenLink to this heading
Returns the length of the array. The lookups available afterwards are those
available for IntegerField. For example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.filter(tags__len=1)
<QuerySet [<Post: Second post>]>
Perubahan indeksLink to this heading
This class of transforms allows you to index into the array in queries. Any
non-negative integer can be used. There are no errors if it exceeds the
size of the array. The lookups available after the
transform are those from the base_field. For
example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.filter(tags__0='thoughts')
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__1__iexact='Django')
<QuerySet [<Post: First post>]>
>>> Post.objects.filter(tags__276='javascript')
<QuerySet []>
Perubahan potonganLink to this heading
This class of transforms allow you to take a slice of the array. Any two non-negative integers can be used, separated by a single underscore. The lookups available after the transform do not change. For example:
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
>>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])
>>> Post.objects.filter(tags__0_1=['thoughts'])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__0_2__contains=['thoughts'])
<QuerySet [<Post: First post>, <Post: Second post>]>
Mengindeks ArrayFieldLink to this heading
At present using db_index will create a
btree index. This does not offer particularly significant help to querying.
A more useful index is a GIN index, which you should create using a
RunSQL operation.
HStoreFieldLink to this heading
- class HStoreField(**options)Link to this definition
A field for storing mappings of strings to strings. The Python data type used is a
dict.Untuk menggunakan bidang ini, anda akan butuh untuk:
Tambah
'django.contrib.postgres'dalamINSTALLED_APPSanda.Setup the hstore extension di PostgreSQL.
Anda akan melihat sebuah kesalahan seperti
can't adapt type 'dict'jika anda melewati langkah pertama, atautype "hstore" does not existjika anda melewati kedua.
Meminta HStoreFieldLink to this heading
In addition to the ability to query by key, there are a number of custom
lookups available for HStoreField.
Kami akan menggunakan model contoh berikut:
from django.contrib.postgres.fields import HStoreField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = HStoreField()
def __str__(self): # __unicode__ on Python 2
return self.name
Kunci pencarianLink to this heading
To query based on a given key, you simply use that key as the lookup name:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>
You can chain other lookups after key lookups:
>>> Dog.objects.filter(data__breed__contains='l')
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
If the key you wish to query by clashes with the name of another lookup, you
need to use the hstorefield.contains lookup instead.
containsLink to this heading
The contains lookup is overridden on
HStoreField. The returned objects are
those where the given dict of key-value pairs are all contained in the
field. It uses the SQL operator @>. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.create(name='Fred', data={})
>>> Dog.objects.filter(data__contains={'owner': 'Bob'})
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
>>> Dog.objects.filter(data__contains={'breed': 'collie'})
<QuerySet [<Dog: Meg>]>
contained_byLink to this heading
This is the inverse of the contains lookup -
the objects returned will be those where the key-value pairs on the object are
a subset of those in the value passed. It uses the SQL operator <@. For
example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.create(name='Fred', data={})
>>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
<QuerySet [<Dog: Meg>, <Dog: Fred>]>
>>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
<QuerySet [<Dog: Fred>]>
has_keyLink to this heading
Returns objects where the given key is in the data. Uses the SQL operator
?. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.filter(data__has_key='owner')
<QuerySet [<Dog: Meg>]>
has_any_keysLink to this heading
Returns objects where any of the given keys are in the data. Uses the SQL
operator ?|. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
>>> Dog.objects.create(name='Fred', data={})
>>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
has_keysLink to this heading
Returns objects where all of the given keys are in the data. Uses the SQL operator
?&. For example:
>>> Dog.objects.create(name='Rufus', data={})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
<QuerySet [<Dog: Meg>]>
keysLink to this heading
Returns objects where the array of keys is the given value. Note that the order
is not guaranteed to be reliable, so this transform is mainly useful for using
in conjunction with lookups on
ArrayField. Uses the SQL function
akeys(). For example:
>>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.filter(data__keys__overlap=['breed', 'toy'])
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
valuesLink to this heading
Returns objects where the array of values is the given value. Note that the
order is not guaranteed to be reliable, so this transform is mainly useful for
using in conjunction with lookups on
ArrayField. Uses the SQL function
avalues(). For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
>>> Dog.objects.filter(data__values__contains=['collie'])
<QuerySet [<Dog: Meg>]>
JSONFieldLink to this heading
- class JSONField(**options)Link to this definition
A field for storing JSON encoded data. In Python the data is represented in its Python native format: dictionaries, lists, strings, numbers, booleans and
None.If you want to store other data types, you'll need to serialize them first. For example, you might cast a
datetimeto a string. You might also want to convert the string back to adatetimewhen you retrieve the data from the database. There are some third-partyJSONFieldimplementations which do this sort of thing automatically.If you give the field a
default, ensure it's a callable such asdict(for an empty default) or a callable that returns a dict (such as a function). Incorrectly usingdefault={}creates a mutable default that is shared between all instances ofJSONField.
Meminta JSONFieldLink to this heading
Kami akan menggunakan model contoh berikut:
from django.contrib.postgres.fields import JSONField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = JSONField()
def __str__(self): # __unicode__ on Python 2
return self.name
Kunci, indeks, dan pencarian kalurLink to this heading
Untuk meminta berdasarkan kunci kamus yang diberikan, cukup gunakan kunci itu sebagai nama pencarian:
>>> Dog.objects.create(name='Rufus', data={
... 'breed': 'labrador',
... 'owner': {
... 'name': 'Bob',
... 'other_pets': [{
... 'name': 'Fishy',
... }],
... },
... })
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>
Multiple keys can be chained together to form a path lookup:
>>> Dog.objects.filter(data__owner__name='Bob')
<QuerySet [<Dog: Rufus>]>
Jika kunci adalah sebuah integer, itu akan ditafsirkan sebagai sebuah pencarian indeks dalam sebuah larik:
>>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
<QuerySet [<Dog: Rufus>]>
If the key you wish to query by clashes with the name of another lookup, use
the jsonfield.contains lookup instead.
If only one key or index is used, the SQL operator -> is used. If multiple
operators are used then the #> operator is used.
Containment and key operationsLink to this heading
JSONField berbagi pencarian terkait pada penahanan dan kunci dengan HStoreField.
contains(menerima JSON apapun daripada hanya sebuah kamus dari string)contained_by(menerima JSON apapun daripada hanya sebuah kamus dari string):lookup
Bidang JangkauanLink to this heading
There are five range field types, corresponding to the built-in range types in PostgreSQL. These fields are used to store a range of values; for example the start and end timestamps of an event, or the range of ages an activity is suitable for.
All of the range fields translate to psycopg2 Range objects in python, but also accept tuples as input if no bounds
information is necessary. The default is lower bound included, upper bound
excluded; that is, [).
IntegerRangeFieldLink to this heading
- class IntegerRangeField(**options)Link to this definition
Stores a range of integers. Based on an
IntegerField. Represented by anint4rangein the database and aNumericRangein Python.Regardless of the bounds specified when saving the data, PostgreSQL always returns a range in a canonical form that includes the lower bound and excludes the upper bound; that is
[).
BigIntegerRangeFieldLink to this heading
- class BigIntegerRangeField(**options)Link to this definition
Stores a range of large integers. Based on a
BigIntegerField. Represented by anint8rangein the database and aNumericRangein Python.Regardless of the bounds specified when saving the data, PostgreSQL always returns a range in a canonical form that includes the lower bound and excludes the upper bound; that is
[).
FloatRangeFieldLink to this heading
- class FloatRangeField(**options)Link to this definition
Stores a range of floating point values. Based on a
FloatField. Represented by anumrangein the database and aNumericRangein Python.
DateTimeRangeFieldLink to this heading
- class DateTimeRangeField(**options)Link to this definition
Stores a range of timestamps. Based on a
DateTimeField. Represented by atztsrangein the database and aDateTimeTZRangein Python.
DateRangeFieldLink to this heading
- class DateRangeField(**options)Link to this definition
Stores a range of dates. Based on a
DateField. Represented by adaterangein the database and aDateRangein Python.Regardless of the bounds specified when saving the data, PostgreSQL always returns a range in a canonical form that includes the lower bound and excludes the upper bound; that is
[).
Querying Range FieldsLink to this heading
There are a number of custom lookups and transforms for range fields. They are available on all the above fields, but we will use the following example model:
from django.contrib.postgres.fields import IntegerRangeField
from django.db import models
class Event(models.Model):
name = models.CharField(max_length=200)
ages = IntegerRangeField()
start = models.DateTimeField()
def __str__(self): # __unicode__ on Python 2
return self.name
We will also use the following example objects:
>>> import datetime
>>> from django.utils import timezone
>>> now = timezone.now()
>>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)
>>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))
and NumericRange:
>>> from psycopg2.extras import NumericRange
Containment functionsLink to this heading
As with other PostgreSQL fields, there are three standard containment
operators: contains, contained_by and overlap, using the SQL
operators @>, <@, and && respectively.
containsLink to this heading
>>> Event.objects.filter(ages__contains=NumericRange(4, 5))
<QuerySet [<Event: Soft play>]>
contained_byLink to this heading
>>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
<QuerySet [<Event: Soft play>]>
The contained_by lookup is also available on the non-range field types:
IntegerField,
BigIntegerField,
FloatField, DateField,
and DateTimeField. For example:
>>> from psycopg2.extras import DateTimeTZRange
>>> Event.objects.filter(start__contained_by=DateTimeTZRange(
... timezone.now() - datetime.timedelta(hours=1),
... timezone.now() + datetime.timedelta(hours=1),
... )
<QuerySet [<Event: Soft play>]>
overlapLink to this heading
>>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
<QuerySet [<Event: Soft play>]>
Fungsi perbandinganLink to this heading
Range fields support the standard lookups: lt, gt,
lte and gte. These are not particularly helpful - they
compare the lower bounds first and then the upper bounds only if necessary.
This is also the strategy used to order by a range field. It is better to use
the specific range comparison operators.
fully_ltLink to this heading
The returned ranges are strictly less than the passed range. In other words, all the points in the returned range are less than all those in the passed range.
>>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
<QuerySet [<Event: Soft play>]>
fully_gtLink to this heading
The returned ranges are strictly greater than the passed range. In other words, the all the points in the returned range are greater than all those in the passed range.
>>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
<QuerySet [<Event: Pub trip>]>
not_ltLink to this heading
The returned ranges do not contain any points less than the passed range, that is the lower bound of the returned range is at least the lower bound of the passed range.
>>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>
not_gtLink to this heading
The returned ranges do not contain any points greater than the passed range, that is the upper bound of the returned range is at most the upper bound of the passed range.
>>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
<QuerySet [<Event: Soft play>]>
adjacent_toLink to this heading
The returned ranges share a bound with the passed range.
>>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>
Querying using the boundsLink to this heading
There are three transforms available for use in queries. You can extract the lower or upper bound, or query based on emptiness.
startswithLink to this heading
Returned objects have the given lower bound. Can be chained to valid lookups for the base field.
>>> Event.objects.filter(ages__startswith=21)
<QuerySet [<Event: Pub trip>]>
endswithLink to this heading
Returned objects have the given upper bound. Can be chained to valid lookups for the base field.
>>> Event.objects.filter(ages__endswith=10)
<QuerySet [<Event: Soft play>]>
isemptyLink to this heading
Returned objects are empty ranges. Can be chained to valid lookups for a
BooleanField.
>>> Event.objects.filter(ages__isempty=True)
<QuerySet []>
Menentukan jenis jangkauan anda sendiriLink to this heading
PostgreSQL allows the definition of custom range types. Django's model and form
field implementations use base classes below, and psycopg2 provides a
register_range() to allow use of custom range
types.
- class RangeField(**options)Link to this definition
Base class for model range fields.
- base_fieldLink to this definition
The model field class to use.
- range_typeLink to this definition
The psycopg2 range type to use.
- form_fieldLink to this definition
The form field class to use. Should be a subclass of
django.contrib.postgres.forms.BaseRangeField.
- class django.contrib.postgres.forms.BaseRangeFieldLink to this definition
Base class for form range fields.
- base_fieldLink to this definition
The form field to use.
- range_typeLink to this definition
The psycopg2 range type to use.