doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
class StringAgg(expression, delimiter, distinct=False, filter=None, default=None, ordering=())
Returns the input values concatenated into a string, separated by the delimiter string, or default if there are no values.
delimiter
Required argument. Needs to be a string.
distinct
An optional boolean argument that determines if concatenated values will be distinct. Defaults to False.
ordering
An optional string of a field name (with an optional "-" prefix which indicates descending order) or an expression (or a tuple or list of strings and/or expressions) that specifies the ordering of the elements in the result string. Examples are the same as for ArrayAgg.ordering.
Deprecated since version 4.0: If there are no rows and default is not provided, StringAgg returns an empty string instead of None. This behavior is deprecated and will be removed in Django 5.0. If you need it, explicitly set default to Value(''). | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.StringAgg |
delimiter
Required argument. Needs to be a string. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.StringAgg.delimiter |
distinct
An optional boolean argument that determines if concatenated values will be distinct. Defaults to False. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.StringAgg.distinct |
ordering
An optional string of a field name (with an optional "-" prefix which indicates descending order) or an expression (or a tuple or list of strings and/or expressions) that specifies the ordering of the elements in the result string. Examples are the same as for ArrayAgg.ordering. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.StringAgg.ordering |
class ExclusionConstraint(*, name, expressions, index_type=None, condition=None, deferrable=None, include=None, opclasses=())
Creates an exclusion constraint in the database. Internally, PostgreSQL implements exclusion constraints using indexes. The default index type is GiST. To use them, you need to activate the btree_gist extension on PostgreSQL. You can install it using the BtreeGistExtension migration operation. If you attempt to insert a new row that conflicts with an existing row, an IntegrityError is raised. Similarly, when update conflicts with an existing row. | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint |
ExclusionConstraint.condition | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.condition |
ExclusionConstraint.deferrable | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.deferrable |
ExclusionConstraint.expressions | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.expressions |
ExclusionConstraint.include | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.include |
ExclusionConstraint.index_type | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.index_type |
ExclusionConstraint.name | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.name |
ExclusionConstraint.opclasses | django.ref.contrib.postgres.constraints#django.contrib.postgres.constraints.ExclusionConstraint.opclasses |
class ArraySubquery(queryset) | django.ref.contrib.postgres.expressions#django.contrib.postgres.expressions.ArraySubquery |
class ArrayField(base_field, size=None, **options)
A field for storing lists of data. Most field types can be used, and you pass another field instance as the base_field. You may also specify a size. ArrayField can be nested to store multi-dimensional arrays. If you give the field a default, ensure it’s a callable such as list (for an empty default) or a callable that returns a list (such as a function). Incorrectly using default=[] creates a mutable default that is shared between all instances of ArrayField.
base_field
This is a required argument. 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 an IntegerField or a CharField. Most field types are permitted, with the exception of those handling relational data (ForeignKey, OneToOneField and ManyToManyField). It is possible to nest array fields - you can specify an instance of ArrayField as the base_field. For example: from django.contrib.postgres.fields import ArrayField
from django.db import models
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.
size
This is an optional argument. 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. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.ArrayField |
base_field
This is a required argument. 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 an IntegerField or a CharField. Most field types are permitted, with the exception of those handling relational data (ForeignKey, OneToOneField and ManyToManyField). It is possible to nest array fields - you can specify an instance of ArrayField as the base_field. For example: from django.contrib.postgres.fields import ArrayField
from django.db import models
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. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.ArrayField.base_field |
size
This is an optional argument. 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. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.ArrayField.size |
class BigIntegerRangeField(**options)
Stores a range of large integers. Based on a BigIntegerField. Represented by an int8range in the database and a NumericRange in 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 [). | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.BigIntegerRangeField |
class CICharField(**options) | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.CICharField |
class CIEmailField(**options) | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.CIEmailField |
class CIText(**options)
A mixin to create case-insensitive text fields backed by the citext type. Read about the performance considerations prior to using it. To use citext, use the CITextExtension operation to set up the citext extension in PostgreSQL before the first CreateModel migration operation. If you’re using an ArrayField of CIText fields, you must add 'django.contrib.postgres' in your INSTALLED_APPS, otherwise field values will appear as strings like '{thoughts,django}'. Several fields that use the mixin are provided: | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.CIText |
class CITextField(**options)
These fields subclass CharField, EmailField, and TextField, respectively. max_length won’t be enforced in the database since citext behaves similar to PostgreSQL’s text type. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.CITextField |
class DateRangeField(**options)
Stores a range of dates. Based on a DateField. Represented by a daterange in the database and a DateRange in 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 [). | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.DateRangeField |
class DateTimeRangeField(**options)
Stores a range of timestamps. Based on a DateTimeField. Represented by a tstzrange in the database and a DateTimeTZRange in Python. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.DateTimeRangeField |
class DecimalRangeField(**options)
Stores a range of floating point values. Based on a DecimalField. Represented by a numrange in the database and a NumericRange in Python. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.DecimalRangeField |
class django.contrib.postgres.forms.BaseRangeField
Base class for form range fields.
base_field
The form field to use.
range_type
The psycopg2 range type to use. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.django.contrib.postgres.forms.BaseRangeField |
base_field
The form field to use. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.django.contrib.postgres.forms.BaseRangeField.base_field |
range_type
The psycopg2 range type to use. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.django.contrib.postgres.forms.BaseRangeField.range_type |
class HStoreField(**options)
A field for storing key-value pairs. The Python data type used is a dict. Keys must be strings, and values may be either strings or nulls (None in Python). To use this field, you’ll need to: Add 'django.contrib.postgres' in your INSTALLED_APPS.
Set up the hstore extension in PostgreSQL. You’ll see an error like can't adapt type 'dict' if you skip the first step, or type "hstore" does not exist if you skip the second. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.HStoreField |
class IntegerRangeField(**options)
Stores a range of integers. Based on an IntegerField. Represented by an int4range in the database and a NumericRange in 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 [). | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.IntegerRangeField |
class RangeBoundary(inclusive_lower=True, inclusive_upper=False)
inclusive_lower
If True (default), the lower bound is inclusive '[', otherwise it’s exclusive '('.
inclusive_upper
If False (default), the upper bound is exclusive ')', otherwise it’s inclusive ']'. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeBoundary |
inclusive_lower
If True (default), the lower bound is inclusive '[', otherwise it’s exclusive '('. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeBoundary.inclusive_lower |
inclusive_upper
If False (default), the upper bound is exclusive ')', otherwise it’s inclusive ']'. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeBoundary.inclusive_upper |
class RangeField(**options)
Base class for model range fields.
base_field
The model field class to use.
range_type
The psycopg2 range type to use.
form_field
The form field class to use. Should be a subclass of django.contrib.postgres.forms.BaseRangeField. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeField |
base_field
The model field class to use. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeField.base_field |
form_field
The form field class to use. Should be a subclass of django.contrib.postgres.forms.BaseRangeField. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeField.form_field |
range_type
The psycopg2 range type to use. | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeField.range_type |
class RangeOperators | django.ref.contrib.postgres.fields#django.contrib.postgres.fields.RangeOperators |
class DateRangeField
Based on DateField and translates its input into DateRange. Default for DateRangeField. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.DateRangeField |
class DateTimeRangeField
Based on DateTimeField and translates its input into DateTimeTZRange. Default for DateTimeRangeField. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.DateTimeRangeField |
class DecimalRangeField
Based on DecimalField and translates its input into NumericRange. Default for DecimalRangeField. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.DecimalRangeField |
class HStoreField
A field which accepts JSON encoded data for an HStoreField. It casts all values (except nulls) to strings. It is represented by an HTML <textarea>. User friendly forms HStoreField is not particularly user friendly in most cases, however it is a useful way to format data from a client-side widget for submission to the server. Note On occasions it may be useful to require or restrict the keys which are valid for a given field. This can be done using the KeysValidator. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.HStoreField |
class IntegerRangeField
Based on IntegerField and translates its input into NumericRange. Default for IntegerRangeField and BigIntegerRangeField. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.IntegerRangeField |
class RangeWidget(base_widget, attrs=None)
Widget used by all of the range fields. Based on MultiWidget. RangeWidget has one required argument:
base_widget
A RangeWidget comprises a 2-tuple of base_widget.
decompress(value)
Takes a single “compressed” value of a field, for example a DateRangeField, and returns a tuple representing a lower and upper bound. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.RangeWidget |
base_widget
A RangeWidget comprises a 2-tuple of base_widget. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.RangeWidget.base_widget |
decompress(value)
Takes a single “compressed” value of a field, for example a DateRangeField, and returns a tuple representing a lower and upper bound. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.RangeWidget.decompress |
class SimpleArrayField(base_field, delimiter=', ', max_length=None, min_length=None)
A field which maps to an array. It is represented by an HTML <input>.
base_field
This is a required argument. It specifies the underlying form field for the array. This is not used to render any HTML, but it is used to process the submitted data and validate it. For example: >>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField
>>> class NumberListForm(forms.Form):
... numbers = SimpleArrayField(forms.IntegerField())
>>> form = NumberListForm({'numbers': '1,2,3'})
>>> form.is_valid()
True
>>> form.cleaned_data
{'numbers': [1, 2, 3]}
>>> form = NumberListForm({'numbers': '1,2,a'})
>>> form.is_valid()
False
delimiter
This is an optional argument which defaults to a comma: ,. This value is used to split the submitted data. It allows you to chain SimpleArrayField for multidimensional data: >>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField
>>> class GridForm(forms.Form):
... places = SimpleArrayField(SimpleArrayField(IntegerField()), delimiter='|')
>>> form = GridForm({'places': '1,2|2,1|4,3'})
>>> form.is_valid()
True
>>> form.cleaned_data
{'places': [[1, 2], [2, 1], [4, 3]]}
Note The field does not support escaping of the delimiter, so be careful in cases where the delimiter is a valid character in the underlying field. The delimiter does not need to be only one character.
max_length
This is an optional argument which validates that the array does not exceed the stated length.
min_length
This is an optional argument which validates that the array reaches at least the stated length.
User friendly forms SimpleArrayField is not particularly user friendly in most cases, however it is a useful way to format data from a client-side widget for submission to the server. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SimpleArrayField |
base_field
This is a required argument. It specifies the underlying form field for the array. This is not used to render any HTML, but it is used to process the submitted data and validate it. For example: >>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField
>>> class NumberListForm(forms.Form):
... numbers = SimpleArrayField(forms.IntegerField())
>>> form = NumberListForm({'numbers': '1,2,3'})
>>> form.is_valid()
True
>>> form.cleaned_data
{'numbers': [1, 2, 3]}
>>> form = NumberListForm({'numbers': '1,2,a'})
>>> form.is_valid()
False | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SimpleArrayField.base_field |
delimiter
This is an optional argument which defaults to a comma: ,. This value is used to split the submitted data. It allows you to chain SimpleArrayField for multidimensional data: >>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField
>>> class GridForm(forms.Form):
... places = SimpleArrayField(SimpleArrayField(IntegerField()), delimiter='|')
>>> form = GridForm({'places': '1,2|2,1|4,3'})
>>> form.is_valid()
True
>>> form.cleaned_data
{'places': [[1, 2], [2, 1], [4, 3]]}
Note The field does not support escaping of the delimiter, so be careful in cases where the delimiter is a valid character in the underlying field. The delimiter does not need to be only one character. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SimpleArrayField.delimiter |
max_length
This is an optional argument which validates that the array does not exceed the stated length. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SimpleArrayField.max_length |
min_length
This is an optional argument which validates that the array reaches at least the stated length. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SimpleArrayField.min_length |
class SplitArrayField(base_field, size, remove_trailing_nulls=False)
This field handles arrays by reproducing the underlying field a fixed number of times.
base_field
This is a required argument. It specifies the form field to be repeated.
size
This is the fixed number of times the underlying field will be used.
remove_trailing_nulls
By default, this is set to False. When False, each value from the repeated fields is stored. When set to True, any trailing values which are blank will be stripped from the result. If the underlying field has required=True, but remove_trailing_nulls is True, then null values are only allowed at the end, and will be stripped. Some examples: SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=False)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> ValidationError - third entry required.
['1', '', '3'] # -> ValidationError - second entry required.
['', '2', ''] # -> ValidationError - first and third entries required.
SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=False)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2, None]
['1', '', '3'] # -> [1, None, 3]
['', '2', ''] # -> [None, 2, None]
SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=True)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2]
['1', '', '3'] # -> ValidationError - second entry required.
['', '2', ''] # -> ValidationError - first entry required.
SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=True)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2]
['1', '', '3'] # -> [1, None, 3]
['', '2', ''] # -> [None, 2] | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SplitArrayField |
base_field
This is a required argument. It specifies the form field to be repeated. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SplitArrayField.base_field |
remove_trailing_nulls
By default, this is set to False. When False, each value from the repeated fields is stored. When set to True, any trailing values which are blank will be stripped from the result. If the underlying field has required=True, but remove_trailing_nulls is True, then null values are only allowed at the end, and will be stripped. Some examples: SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=False)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> ValidationError - third entry required.
['1', '', '3'] # -> ValidationError - second entry required.
['', '2', ''] # -> ValidationError - first and third entries required.
SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=False)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2, None]
['1', '', '3'] # -> [1, None, 3]
['', '2', ''] # -> [None, 2, None]
SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=True)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2]
['1', '', '3'] # -> ValidationError - second entry required.
['', '2', ''] # -> ValidationError - first entry required.
SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=True)
['1', '2', '3'] # -> [1, 2, 3]
['1', '2', ''] # -> [1, 2]
['1', '', '3'] # -> [1, None, 3]
['', '2', ''] # -> [None, 2] | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SplitArrayField.remove_trailing_nulls |
size
This is the fixed number of times the underlying field will be used. | django.ref.contrib.postgres.forms#django.contrib.postgres.forms.SplitArrayField.size |
class RandomUUID | django.ref.contrib.postgres.functions#django.contrib.postgres.functions.RandomUUID |
class TransactionNow | django.ref.contrib.postgres.functions#django.contrib.postgres.functions.TransactionNow |
class BloomIndex(*expressions, length=None, columns=(), **options)
Creates a bloom index. To use this index access you need to activate the bloom extension on PostgreSQL. You can install it using the BloomExtension migration operation. Provide an integer number of bits from 1 to 4096 to the length parameter to specify the length of each index entry. PostgreSQL’s default is 80. The columns argument takes a tuple or list of up to 32 values that are integer number of bits from 1 to 4095. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.BloomIndex |
class BrinIndex(*expressions, autosummarize=None, pages_per_range=None, **options)
Creates a BRIN index. Set the autosummarize parameter to True to enable automatic summarization to be performed by autovacuum. The pages_per_range argument takes a positive integer. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.BrinIndex |
class BTreeIndex(*expressions, fillfactor=None, **options)
Creates a B-Tree index. Provide an integer value from 10 to 100 to the fillfactor parameter to tune how packed the index pages will be. PostgreSQL’s default is 90. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.BTreeIndex |
class GinIndex(*expressions, fastupdate=None, gin_pending_list_limit=None, **options)
Creates a gin index. To use this index on data types not in the built-in operator classes, you need to activate the btree_gin extension on PostgreSQL. You can install it using the BtreeGinExtension migration operation. Set the fastupdate parameter to False to disable the GIN Fast Update Technique that’s enabled by default in PostgreSQL. Provide an integer number of bytes to the gin_pending_list_limit parameter to tune the maximum size of the GIN pending list which is used when fastupdate is enabled. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.GinIndex |
class GistIndex(*expressions, buffering=None, fillfactor=None, **options)
Creates a GiST index. These indexes are automatically created on spatial fields with spatial_index=True. They’re also useful on other types, such as HStoreField or the range fields. To use this index on data types not in the built-in gist operator classes, you need to activate the btree_gist extension on PostgreSQL. You can install it using the BtreeGistExtension migration operation. Set the buffering parameter to True or False to manually enable or disable buffering build of the index. Provide an integer value from 10 to 100 to the fillfactor parameter to tune how packed the index pages will be. PostgreSQL’s default is 90. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.GistIndex |
class HashIndex(*expressions, fillfactor=None, **options)
Creates a hash index. Provide an integer value from 10 to 100 to the fillfactor parameter to tune how packed the index pages will be. PostgreSQL’s default is 90. Use this index only on PostgreSQL 10 and later Hash indexes have been available in PostgreSQL for a long time, but they suffer from a number of data integrity issues in older versions. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.HashIndex |
class OpClass(expression, name)
An OpClass() expression represents the expression with a custom operator class that can be used to define functional indexes or unique constraints. To use it, you need to add 'django.contrib.postgres' in your INSTALLED_APPS. Set the name parameter to the name of the operator class. For example: Index(
OpClass(Lower('username'), name='varchar_pattern_ops'),
name='lower_username_idx',
)
creates an index on Lower('username') using varchar_pattern_ops. Another example: UniqueConstraint(
OpClass(Upper('description'), name='text_pattern_ops'),
name='upper_description_unique',
)
creates a unique constraint on Upper('description') using text_pattern_ops. Changed in Django 4.0: Support for functional unique constraints was added. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.OpClass |
class SpGistIndex(*expressions, fillfactor=None, **options)
Creates an SP-GiST index. Provide an integer value from 10 to 100 to the fillfactor parameter to tune how packed the index pages will be. PostgreSQL’s default is 90. Changed in Django 3.2: Positional argument *expressions was added in order to support functional indexes. | django.ref.contrib.postgres.indexes#django.contrib.postgres.indexes.SpGistIndex |
class AddConstraintNotValid(model_name, constraint)
Like AddConstraint, but avoids validating the constraint on existing rows. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.AddConstraintNotValid |
class AddIndexConcurrently(model_name, index)
Like AddIndex, but creates an index with the CONCURRENTLY option. This has a few caveats to be aware of when using this option, see the PostgreSQL documentation of building indexes concurrently. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.AddIndexConcurrently |
class BloomExtension
Installs the bloom extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.BloomExtension |
class BtreeGinExtension
Installs the btree_gin extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.BtreeGinExtension |
class BtreeGistExtension
Installs the btree_gist extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.BtreeGistExtension |
class CITextExtension
Installs the citext extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.CITextExtension |
class CreateCollation(name, locale, *, provider='libc', deterministic=True)
Creates a collation with the given name, locale and provider. Set the deterministic parameter to False to create a non-deterministic collation, such as for case-insensitive filtering. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.CreateCollation |
class CreateExtension(name)
An Operation subclass which installs a PostgreSQL extension. For common extensions, use one of the more specific subclasses below.
name
This is a required argument. The name of the extension to be installed. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.CreateExtension |
name
This is a required argument. The name of the extension to be installed. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.CreateExtension.name |
class CryptoExtension
Installs the pgcrypto extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.CryptoExtension |
class HStoreExtension
Installs the hstore extension and also sets up the connection to interpret hstore data for possible use in subsequent migrations. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.HStoreExtension |
class RemoveCollation(name, locale, *, provider='libc', deterministic=True)
Removes the collations named name. When reversed this is creating a collation with the provided locale, provider, and deterministic arguments. Therefore, locale is required to make this operation reversible. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.RemoveCollation |
class RemoveIndexConcurrently(model_name, name)
Like RemoveIndex, but removes the index with the CONCURRENTLY option. This has a few caveats to be aware of when using this option, see the PostgreSQL documentation. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.RemoveIndexConcurrently |
class TrigramExtension
Installs the pg_trgm extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.TrigramExtension |
class UnaccentExtension
Installs the unaccent extension. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.UnaccentExtension |
class ValidateConstraint(model_name, name)
Scans through the table and validates the given check constraint on existing rows. | django.ref.contrib.postgres.operations#django.contrib.postgres.operations.ValidateConstraint |
class SearchHeadline(expression, query, config=None, start_sel=None, stop_sel=None, max_words=None, min_words=None, short_word=None, highlight_all=None, max_fragments=None, fragment_delimiter=None) | django.ref.contrib.postgres.search#django.contrib.postgres.search.SearchHeadline |
class SearchQuery(value, config=None, search_type='plain') | django.ref.contrib.postgres.search#django.contrib.postgres.search.SearchQuery |
class SearchRank(vector, query, weights=None, normalization=None, cover_density=False) | django.ref.contrib.postgres.search#django.contrib.postgres.search.SearchRank |
class SearchVector(*expressions, config=None, weight=None) | django.ref.contrib.postgres.search#django.contrib.postgres.search.SearchVector |
class SearchVectorField | django.ref.contrib.postgres.search#django.contrib.postgres.search.SearchVectorField |
class TrigramDistance(expression, string, **extra) | django.ref.contrib.postgres.search#django.contrib.postgres.search.TrigramDistance |
class TrigramSimilarity(expression, string, **extra) | django.ref.contrib.postgres.search#django.contrib.postgres.search.TrigramSimilarity |
class TrigramWordDistance(string, expression, **extra) | django.ref.contrib.postgres.search#django.contrib.postgres.search.TrigramWordDistance |
class TrigramWordSimilarity(string, expression, **extra) | django.ref.contrib.postgres.search#django.contrib.postgres.search.TrigramWordSimilarity |
class KeysValidator(keys, strict=False, messages=None)
Validates that the given keys are contained in the value. If strict is True, then it also checks that there are no other keys present. The messages passed should be a dict containing the keys missing_keys and/or extra_keys. Note Note that this checks only for the existence of a given key, not that the value of a key is non-empty. | django.ref.contrib.postgres.validators#django.contrib.postgres.validators.KeysValidator |
class RangeMaxValueValidator(limit_value, message=None)
Validates that the upper bound of the range is not greater than limit_value. | django.ref.contrib.postgres.validators#django.contrib.postgres.validators.RangeMaxValueValidator |
class RangeMinValueValidator(limit_value, message=None)
Validates that the lower bound of the range is not less than the limit_value. | django.ref.contrib.postgres.validators#django.contrib.postgres.validators.RangeMinValueValidator |
class middleware.RedirectFallbackMiddleware
You can change the HttpResponse classes used by the middleware by creating a subclass of RedirectFallbackMiddleware and overriding response_gone_class and/or response_redirect_class.
response_gone_class
The HttpResponse class used when a Redirect is not found for the requested path or has a blank new_path value. Defaults to HttpResponseGone.
response_redirect_class
The HttpResponse class that handles the redirect. Defaults to HttpResponsePermanentRedirect. | django.ref.contrib.redirects#django.contrib.redirects.middleware.RedirectFallbackMiddleware |
response_gone_class
The HttpResponse class used when a Redirect is not found for the requested path or has a blank new_path value. Defaults to HttpResponseGone. | django.ref.contrib.redirects#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_gone_class |
response_redirect_class
The HttpResponse class that handles the redirect. Defaults to HttpResponsePermanentRedirect. | django.ref.contrib.redirects#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class |
class models.Redirect
Redirects are represented by a standard Django model, which lives in django/contrib/redirects/models.py. You can access redirect objects via the Django database API. For example: >>> from django.conf import settings
>>> from django.contrib.redirects.models import Redirect
>>> # Add a new redirect.
>>> redirect = Redirect.objects.create(
... site_id=1,
... old_path='/contact-us/',
... new_path='/contact/',
... )
>>> # Change a redirect.
>>> redirect.new_path = '/contact-details/'
>>> redirect.save()
>>> redirect
<Redirect: /contact-us/ ---> /contact-details/>
>>> # Delete a redirect.
>>> Redirect.objects.filter(site_id=1, old_path='/contact-us/').delete()
(1, {'redirects.Redirect': 1}) | django.ref.contrib.redirects#django.contrib.redirects.models.Redirect |
SchemaEditor
class BaseDatabaseSchemaEditor
Django’s migration system is split into two parts; the logic for calculating and storing what operations should be run (django.db.migrations), and the database abstraction layer that turns things like “create a model” or “delete a field” into SQL - which is the job of the SchemaEditor. It’s unlikely that you will want to interact directly with SchemaEditor as a normal developer using Django, but if you want to write your own migration system, or have more advanced needs, it’s a lot nicer than writing SQL. Each database backend in Django supplies its own version of SchemaEditor, and it’s always accessible via the connection.schema_editor() context manager: with connection.schema_editor() as schema_editor:
schema_editor.delete_model(MyModel)
It must be used via the context manager as this allows it to manage things like transactions and deferred SQL (like creating ForeignKey constraints). It exposes all possible operations as methods, that should be called in the order you wish changes to be applied. Some possible operations or types of change are not possible on all databases - for example, MyISAM does not support foreign key constraints. If you are writing or maintaining a third-party database backend for Django, you will need to provide a SchemaEditor implementation in order to work with Django’s migration functionality - however, as long as your database is relatively standard in its use of SQL and relational design, you should be able to subclass one of the built-in Django SchemaEditor classes and tweak the syntax a little. Methods execute()
BaseDatabaseSchemaEditor.execute(sql, params=())
Executes the SQL statement passed in, with parameters if supplied. This is a wrapper around the normal database cursors that allows capture of the SQL to a .sql file if the user wishes. create_model()
BaseDatabaseSchemaEditor.create_model(model)
Creates a new table in the database for the provided model, along with any unique constraints or indexes it requires. delete_model()
BaseDatabaseSchemaEditor.delete_model(model)
Drops the model’s table in the database along with any unique constraints or indexes it has. add_index()
BaseDatabaseSchemaEditor.add_index(model, index)
Adds index to model’s table. remove_index()
BaseDatabaseSchemaEditor.remove_index(model, index)
Removes index from model’s table. add_constraint()
BaseDatabaseSchemaEditor.add_constraint(model, constraint)
Adds constraint to model’s table. remove_constraint()
BaseDatabaseSchemaEditor.remove_constraint(model, constraint)
Removes constraint from model’s table. alter_unique_together()
BaseDatabaseSchemaEditor.alter_unique_together(model, old_unique_together, new_unique_together)
Changes a model’s unique_together value; this will add or remove unique constraints from the model’s table until they match the new value. alter_index_together()
BaseDatabaseSchemaEditor.alter_index_together(model, old_index_together, new_index_together)
Changes a model’s index_together value; this will add or remove indexes from the model’s table until they match the new value. alter_db_table()
BaseDatabaseSchemaEditor.alter_db_table(model, old_db_table, new_db_table)
Renames the model’s table from old_db_table to new_db_table. alter_db_tablespace()
BaseDatabaseSchemaEditor.alter_db_tablespace(model, old_db_tablespace, new_db_tablespace)
Moves the model’s table from one tablespace to another. add_field()
BaseDatabaseSchemaEditor.add_field(model, field)
Adds a column (or sometimes multiple) to the model’s table to represent the field. This will also add indexes or a unique constraint if the field has db_index=True or unique=True. If the field is a ManyToManyField without a value for through, instead of creating a column, it will make a table to represent the relationship. If through is provided, it is a no-op. If the field is a ForeignKey, this will also add the foreign key constraint to the column. remove_field()
BaseDatabaseSchemaEditor.remove_field(model, field)
Removes the column(s) representing the field from the model’s table, along with any unique constraints, foreign key constraints, or indexes caused by that field. If the field is a ManyToManyField without a value for through, it will remove the table created to track the relationship. If through is provided, it is a no-op. alter_field()
BaseDatabaseSchemaEditor.alter_field(model, old_field, new_field, strict=False)
This transforms the field on the model from the old field to the new one. This includes changing the name of the column (the db_column attribute), changing the type of the field (if the field class changes), changing the NULL status of the field, adding or removing field-only unique constraints and indexes, changing primary key, and changing the destination of ForeignKey constraints. The most common transformation this cannot do is transforming a ManyToManyField into a normal Field or vice-versa; Django cannot do this without losing data, and so it will refuse to do it. Instead, remove_field() and add_field() should be called separately. If the database has the supports_combined_alters, Django will try and do as many of these in a single database call as possible; otherwise, it will issue a separate ALTER statement for each change, but will not issue ALTERs where no change is required. Attributes All attributes should be considered read-only unless stated otherwise. connection
SchemaEditor.connection
A connection object to the database. A useful attribute of the connection is alias which can be used to determine the name of the database being accessed. This is useful when doing data migrations for migrations with multiple databases. | django.ref.schema-editor |
Search A common task for web applications is to search some data in the database with user input. In a simple case, this could be filtering a list of objects by a category. A more complex use case might require searching with weighting, categorization, highlighting, multiple languages, and so on. This document explains some of the possible use cases and the tools you can use. We’ll refer to the same models used in Making queries. Use Cases Standard textual queries Text-based fields have a selection of matching operations. For example, you may wish to allow lookup up an author like so: >>> Author.objects.filter(name__contains='Terry')
[<Author: Terry Gilliam>, <Author: Terry Jones>]
This is a very fragile solution as it requires the user to know an exact substring of the author’s name. A better approach could be a case-insensitive match (icontains), but this is only marginally better. A database’s more advanced comparison functions If you’re using PostgreSQL, Django provides a selection of database specific tools to allow you to leverage more complex querying options. Other databases have different selections of tools, possibly via plugins or user-defined functions. Django doesn’t include any support for them at this time. We’ll use some examples from PostgreSQL to demonstrate the kind of functionality databases may have. Searching in other databases All of the searching tools provided by django.contrib.postgres are constructed entirely on public APIs such as custom lookups and database functions. Depending on your database, you should be able to construct queries to allow similar APIs. If there are specific things which cannot be achieved this way, please open a ticket. In the above example, we determined that a case insensitive lookup would be more useful. When dealing with non-English names, a further improvement is to use unaccented comparison: >>> Author.objects.filter(name__unaccent__icontains='Helen')
[<Author: Helen Mirren>, <Author: Helena Bonham Carter>, <Author: Hélène Joy>]
This shows another issue, where we are matching against a different spelling of the name. In this case we have an asymmetry though - a search for Helen will pick up Helena or Hélène, but not the reverse. Another option would be to use a trigram_similar comparison, which compares sequences of letters. For example: >>> Author.objects.filter(name__unaccent__lower__trigram_similar='Hélène')
[<Author: Helen Mirren>, <Author: Hélène Joy>]
Now we have a different problem - the longer name of “Helena Bonham Carter” doesn’t show up as it is much longer. Trigram searches consider all combinations of three letters, and compares how many appear in both search and source strings. For the longer name, there are more combinations that don’t appear in the source string, so it is no longer considered a close match. The correct choice of comparison functions here depends on your particular data set, for example the language(s) used and the type of text being searched. All of the examples we’ve seen are on short strings where the user is likely to enter something close (by varying definitions) to the source data. Document-based search Standard database operations stop being a useful approach when you start considering large blocks of text. Whereas the examples above can be thought of as operations on a string of characters, full text search looks at the actual words. Depending on the system used, it’s likely to use some of the following ideas: Ignoring “stop words” such as “a”, “the”, “and”. Stemming words, so that “pony” and “ponies” are considered similar. Weighting words based on different criteria such as how frequently they appear in the text, or the importance of the fields, such as the title or keywords, that they appear in. There are many alternatives for using searching software, some of the most prominent are Elastic and Solr. These are full document-based search solutions. To use them with data from Django models, you’ll need a layer which translates your data into a textual document, including back-references to the database ids. When a search using the engine returns a certain document, you can then look it up in the database. There are a variety of third-party libraries which are designed to help with this process. PostgreSQL support PostgreSQL has its own full text search implementation built-in. While not as powerful as some other search engines, it has the advantage of being inside your database and so can easily be combined with other relational queries such as categorization. The django.contrib.postgres module provides some helpers to make these queries. For example, a query might select all the blog entries which mention “cheese”: >>> Entry.objects.filter(body_text__search='cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]
You can also filter on a combination of fields and on related models: >>> Entry.objects.annotate(
... search=SearchVector('blog__tagline', 'body_text'),
... ).filter(search='cheese')
[
<Entry: Cheese on Toast recipes>,
<Entry: Pizza Recipes>,
<Entry: Dairy farming in Argentina>,
]
See the contrib.postgres Full text search document for complete details. | django.topics.db.search |
class backends.base.SessionBase
This is the base class for all session objects. It has the following standard dictionary methods:
__getitem__(key)
Example: fav_color = request.session['fav_color']
__setitem__(key, value)
Example: request.session['fav_color'] = 'blue'
__delitem__(key)
Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.
__contains__(key)
Example: 'fav_color' in request.session
get(key, default=None)
Example: fav_color = request.session.get('fav_color', 'red')
pop(key, default=__not_given)
Example: fav_color = request.session.pop('fav_color', 'blue')
keys()
items()
setdefault()
clear()
It also has these methods:
flush()
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).
set_test_cookie()
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information.
test_cookie_worked()
Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.
delete_test_cookie()
Deletes the test cookie. Use this to clean up after yourself.
get_session_cookie_age()
Returns the age of session cookies, in seconds. Defaults to SESSION_COOKIE_AGE.
set_expiry(value)
Sets the expiration time for the session. You can pass a number of different values: If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer. If value is 0, the user’s session cookie will expire when the user’s web browser is closed. If value is None, the session reverts to using the global session expiry policy. Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.
get_expiry_age()
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE. This function accepts two optional keyword arguments:
modification: last modification of the session, as a datetime object. Defaults to the current time.
expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.
get_expiry_date()
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date SESSION_COOKIE_AGE seconds from now. This function accepts the same keyword arguments as get_expiry_age().
get_expire_at_browser_close()
Returns either True or False, depending on whether the user’s session cookie will expire when the user’s web browser is closed.
clear_expired()
Removes expired sessions from the session store. This class method is called by clearsessions.
cycle_key()
Creates a new session key while retaining the current session data. django.contrib.auth.login() calls this method to mitigate against session fixation. | django.topics.http.sessions#django.contrib.sessions.backends.base.SessionBase |
__contains__(key)
Example: 'fav_color' in request.session | django.topics.http.sessions#django.contrib.sessions.backends.base.SessionBase.__contains__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.