doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
HttpResponse.seekable()
Always False. This method makes an HttpResponse instance a stream-like object. | django.ref.request-response#django.http.HttpResponse.seekable |
HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library.
max_age should be an integer number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated.
expires should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated. Use domain if you want to set a cross-domain cookie. For example, domain="example.com" will set a cookie that is readable by the domains www.example.com, blog.example.com, etc. Otherwise, a cookie will only be readable by the domain that set it. Use secure=True if you want the cookie to be only sent to the server when a request is made with the https scheme.
Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie. HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data.
Use samesite='Strict' or samesite='Lax' to tell the browser not to send this cookie when performing a cross-origin request. SameSite isn’t supported by all browsers, so it’s not a replacement for Django’s CSRF protection, but rather a defense in depth measure. Use samesite='None' (string) to explicitly state that this cookie is sent with all same-site and cross-site requests. Warning RFC 6265 states that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size. Django will not raise an exception if there’s an attempt to store a cookie of more than 4096 bytes, but many browsers will not set the cookie correctly. | django.ref.request-response#django.http.HttpResponse.set_cookie |
HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
Like set_cookie(), but cryptographic signing the cookie before setting it. Use in conjunction with HttpRequest.get_signed_cookie(). You can use the optional salt argument for added key strength, but you will need to remember to pass it to the corresponding HttpRequest.get_signed_cookie() call. | django.ref.request-response#django.http.HttpResponse.set_signed_cookie |
HttpResponse.setdefault(header, value)
Sets a header unless it has already been set. | django.ref.request-response#django.http.HttpResponse.setdefault |
HttpResponse.status_code
The HTTP status code for the response. Unless reason_phrase is explicitly set, modifying the value of status_code outside the constructor will also modify the value of reason_phrase. | django.ref.request-response#django.http.HttpResponse.status_code |
HttpResponse.streaming
This is always False. This attribute exists so middleware can treat streaming responses differently from regular responses. | django.ref.request-response#django.http.HttpResponse.streaming |
HttpResponse.tell()
This method makes an HttpResponse instance a file-like object. | django.ref.request-response#django.http.HttpResponse.tell |
HttpResponse.writable()
Always True. This method makes an HttpResponse instance a stream-like object. | django.ref.request-response#django.http.HttpResponse.writable |
HttpResponse.write(content)
This method makes an HttpResponse instance a file-like object. | django.ref.request-response#django.http.HttpResponse.write |
HttpResponse.writelines(lines)
Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object. | django.ref.request-response#django.http.HttpResponse.writelines |
class HttpResponseBadRequest
Acts just like HttpResponse but uses a 400 status code. | django.ref.request-response#django.http.HttpResponseBadRequest |
class HttpResponseForbidden
Acts just like HttpResponse but uses a 403 status code. | django.ref.request-response#django.http.HttpResponseForbidden |
class HttpResponseGone
Acts just like HttpResponse but uses a 410 status code. | django.ref.request-response#django.http.HttpResponseGone |
class HttpResponseNotAllowed
Like HttpResponse, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (e.g. ['GET', 'POST']). | django.ref.request-response#django.http.HttpResponseNotAllowed |
class HttpResponseNotFound
Acts just like HttpResponse but uses a 404 status code. | django.ref.request-response#django.http.HttpResponseNotFound |
class HttpResponseNotModified
The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304). | django.ref.request-response#django.http.HttpResponseNotModified |
class HttpResponsePermanentRedirect
Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a “found” redirect (status code 302). | django.ref.request-response#django.http.HttpResponsePermanentRedirect |
class HttpResponseRedirect
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. 'https://www.yahoo.com/search/'), an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/'). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.
url
This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header). | django.ref.request-response#django.http.HttpResponseRedirect |
url
This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header). | django.ref.request-response#django.http.HttpResponseRedirect.url |
class HttpResponseServerError
Acts just like HttpResponse but uses a 500 status code. | django.ref.request-response#django.http.HttpResponseServerError |
class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences: Its default Content-Type header is set to application/json. The first parameter, data, should be a dict instance. If the safe parameter is set to False (see below) it can be any JSON-serializable object. The encoder, which defaults to django.core.serializers.json.DjangoJSONEncoder, will be used to serialize the data. See JSON serialization for more details about this serializer. The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised. The json_dumps_params parameter is a dictionary of keyword arguments to pass to the json.dumps() call used to generate the response. | django.ref.request-response#django.http.JsonResponse |
class QueryDict | django.ref.request-response#django.http.QueryDict |
QueryDict.__contains__(key)
Returns True if the given key is set. This lets you do, e.g., if "foo"
in request.GET. | django.ref.request-response#django.http.QueryDict.__contains__ |
QueryDict.__getitem__(key)
Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python’s standard KeyError, so you can stick to catching KeyError.) | django.ref.request-response#django.http.QueryDict.__getitem__ |
QueryDict.__init__(query_string=None, mutable=False, encoding=None)
Instantiates a QueryDict object based on query_string. >>> QueryDict('a=1&a=2&c=3')
<QueryDict: {'a': ['1', '2'], 'c': ['3']}>
If query_string is not passed in, the resulting QueryDict will be empty (it will have no keys or values). Most QueryDicts you encounter, and in particular those at request.POST and request.GET, will be immutable. If you are instantiating one yourself, you can make it mutable by passing mutable=True to its __init__(). Strings for setting both keys and values will be converted from encoding to str. If encoding is not set, it defaults to DEFAULT_CHARSET. | django.ref.request-response#django.http.QueryDict.__init__ |
QueryDict.__setitem__(key, value)
Sets the given key to [value] (a list whose single element is value). Note that this, as other dictionary functions that have side effects, can only be called on a mutable QueryDict (such as one that was created via QueryDict.copy()). | django.ref.request-response#django.http.QueryDict.__setitem__ |
QueryDict.appendlist(key, item)
Appends an item to the internal list associated with key. | django.ref.request-response#django.http.QueryDict.appendlist |
QueryDict.copy()
Returns a copy of the object using copy.deepcopy(). This copy will be mutable even if the original was not. | django.ref.request-response#django.http.QueryDict.copy |
QueryDict.dict()
Returns a dict representation of QueryDict. For every (key, list) pair in QueryDict, dict will have (key, item), where item is one element of the list, using the same logic as QueryDict.__getitem__(): >>> q = QueryDict('a=1&a=3&a=5')
>>> q.dict()
{'a': '5'} | django.ref.request-response#django.http.QueryDict.dict |
QueryDict.get(key, default=None)
Uses the same logic as __getitem__(), with a hook for returning a default value if the key doesn’t exist. | django.ref.request-response#django.http.QueryDict.get |
QueryDict.getlist(key, default=None)
Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list. | django.ref.request-response#django.http.QueryDict.getlist |
QueryDict.items()
Like dict.items(), except this uses the same last-value logic as __getitem__() and returns an iterator object instead of a view object. For example: >>> q = QueryDict('a=1&a=2&a=3')
>>> list(q.items())
[('a', '3')] | django.ref.request-response#django.http.QueryDict.items |
QueryDict.lists()
Like items(), except it includes all values, as a list, for each member of the dictionary. For example: >>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])] | django.ref.request-response#django.http.QueryDict.lists |
QueryDict.pop(key)
Returns a list of values for the given key and removes them from the dictionary. Raises KeyError if the key does not exist. For example: >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
>>> q.pop('a')
['1', '2', '3'] | django.ref.request-response#django.http.QueryDict.pop |
QueryDict.popitem()
Removes an arbitrary member of the dictionary (since there’s no concept of ordering), and returns a two value tuple containing the key and a list of all values for the key. Raises KeyError when called on an empty dictionary. For example: >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
>>> q.popitem()
('a', ['1', '2', '3']) | django.ref.request-response#django.http.QueryDict.popitem |
QueryDict.setdefault(key, default=None)
Like dict.setdefault(), except it uses __setitem__() internally. | django.ref.request-response#django.http.QueryDict.setdefault |
QueryDict.setlist(key, list_)
Sets the given key to list_ (unlike __setitem__()). | django.ref.request-response#django.http.QueryDict.setlist |
QueryDict.setlistdefault(key, default_list=None)
Like setdefault(), except it takes a list of values instead of a single value. | django.ref.request-response#django.http.QueryDict.setlistdefault |
QueryDict.update(other_dict)
Takes either a QueryDict or a dictionary. Like dict.update(), except it appends to the current dictionary items rather than replacing them. For example: >>> q = QueryDict('a=1', mutable=True)
>>> q.update({'a': '2'})
>>> q.getlist('a')
['1', '2']
>>> q['a'] # returns the last
'2' | django.ref.request-response#django.http.QueryDict.update |
QueryDict.urlencode(safe=None)
Returns a string of the data in query string format. For example: >>> q = QueryDict('a=2&b=3&b=5')
>>> q.urlencode()
'a=2&b=3&b=5'
Use the safe parameter to pass characters which don’t require encoding. For example: >>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode(safe='/')
'next=/a%26b/' | django.ref.request-response#django.http.QueryDict.urlencode |
QueryDict.values()
Like dict.values(), except this uses the same last-value logic as __getitem__() and returns an iterator instead of a view object. For example: >>> q = QueryDict('a=1&a=2&a=3')
>>> list(q.values())
['3'] | django.ref.request-response#django.http.QueryDict.values |
class StreamingHttpResponse | django.ref.request-response#django.http.StreamingHttpResponse |
StreamingHttpResponse.reason_phrase
The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases. Unless explicitly set, reason_phrase is determined by the value of status_code. | django.ref.request-response#django.http.StreamingHttpResponse.reason_phrase |
StreamingHttpResponse.status_code
The HTTP status code for the response. Unless reason_phrase is explicitly set, modifying the value of status_code outside the constructor will also modify the value of reason_phrase. | django.ref.request-response#django.http.StreamingHttpResponse.status_code |
StreamingHttpResponse.streaming
This is always True. | django.ref.request-response#django.http.StreamingHttpResponse.streaming |
StreamingHttpResponse.streaming_content
An iterator of the response content, bytestring encoded according to HttpResponse.charset. | django.ref.request-response#django.http.StreamingHttpResponse.streaming_content |
Logging See also How to configure and use logging Django logging overview Django’s logging module extends Python’s builtin logging. Logging is configured as part of the general Django django.setup() function, so it’s always available unless explicitly disabled. Django’s default logging configuration By default, Django uses Python’s logging.config.dictConfig format. Default logging conditions The full set of default logging conditions are: When DEBUG is True: The django logger sends messages in the django hierarchy (except django.server) at the INFO level or higher to the console. When DEBUG is False: The django logger sends messages in the django hierarchy (except django.server) with ERROR or CRITICAL level to AdminEmailHandler. Independently of the value of DEBUG: The django.server logger sends messages at the INFO level or higher to the console. All loggers except django.server propagate logging to their parents, up to the root django logger. The console and mail_admins handlers are attached to the root logger to provide the behavior described above. Python’s own defaults send records of level WARNING and higher to the console. Default logging definition Django’s default logging configuration inherits Python’s defaults. It’s available as django.utils.log.DEFAULT_LOGGING and defined in django/utils/log.py: {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'formatters': {
'django.server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[{server_time}] {message}',
'style': '{',
}
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'django.server',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
},
'django.server': {
'handlers': ['django.server'],
'level': 'INFO',
'propagate': False,
},
}
}
See Configuring logging on how to complement or replace this default logging configuration. Django logging extensions Django provides a number of utilities to handle the particular requirements of logging in a web server environment. Loggers Django provides several built-in loggers. django The parent logger for messages in the django named logger hierarchy. Django does not post messages using this name. Instead, it uses one of the loggers below. django.request Log messages related to the handling of requests. 5XX responses are raised as ERROR messages; 4XX responses are raised as WARNING messages. Requests that are logged to the django.security logger aren’t logged to django.request. Messages to this logger have the following extra context:
status_code: The HTTP response code associated with the request.
request: The request object that generated the logging message. django.server Log messages related to the handling of requests received by the server invoked by the runserver command. HTTP 5XX responses are logged as ERROR messages, 4XX responses are logged as WARNING messages, and everything else is logged as INFO. Messages to this logger have the following extra context:
status_code: The HTTP response code associated with the request.
request: The request object that generated the logging message. django.template Log messages related to the rendering of templates. Missing context variables are logged as DEBUG messages. django.db.backends Messages relating to the interaction of code with the database. For example, every application-level SQL statement executed by a request is logged at the DEBUG level to this logger. Messages to this logger have the following extra context:
duration: The time taken to execute the SQL statement.
sql: The SQL statement that was executed.
params: The parameters that were used in the SQL call.
alias: The alias of the database used in the SQL call. For performance reasons, SQL logging is only enabled when settings.DEBUG is set to True, regardless of the logging level or handlers that are installed. This logging does not include framework-level initialization (e.g. SET TIMEZONE) or transaction management queries (e.g. BEGIN, COMMIT, and ROLLBACK). Turn on query logging in your database if you wish to view all database queries. Changed in Django 4.0: The database alias was added to log messages. django.security.* The security loggers will receive messages on any occurrence of SuspiciousOperation and other security-related errors. There is a sub-logger for each subtype of security error, including all SuspiciousOperations. The level of the log event depends on where the exception is handled. Most occurrences are logged as a warning, while any SuspiciousOperation that reaches the WSGI handler will be logged as an error. For example, when an HTTP Host header is included in a request from a client that does not match ALLOWED_HOSTS, Django will return a 400 response, and an error message will be logged to the django.security.DisallowedHost logger. These log events will reach the django logger by default, which mails error events to admins when DEBUG=False. Requests resulting in a 400 response due to a SuspiciousOperation will not be logged to the django.request logger, but only to the django.security logger. To silence a particular type of SuspiciousOperation, you can override that specific logger following this example: 'handlers': {
'null': {
'class': 'logging.NullHandler',
},
},
'loggers': {
'django.security.DisallowedHost': {
'handlers': ['null'],
'propagate': False,
},
},
Other django.security loggers not based on SuspiciousOperation are:
django.security.csrf: For CSRF failures. django.db.backends.schema Logs the SQL queries that are executed during schema changes to the database by the migrations framework. Note that it won’t log the queries executed by RunPython. Messages to this logger have params and sql in their extra context (but unlike django.db.backends, not duration). The values have the same meaning as explained in django.db.backends. Handlers Django provides one log handler in addition to those provided by the
Python logging module.
class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)
This handler sends an email to the site ADMINS for each log message it receives. If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase “internal IP” if the client’s IP address is in the INTERNAL_IPS setting; if not, it will include “EXTERNAL IP”. If the log record contains stack trace information, that stack trace will be included in the email. The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this: 'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
},
Be aware of the security implications of logging when using the AdminEmailHandler. By setting the email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden, like this: 'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
},
},
By default, an instance of the email backend specified in EMAIL_BACKEND will be used. The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this: 'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
'reporter_class': 'somepackage.error_reporter.CustomErrorReporter',
},
},
send_mail(subject, message, *args, **kwargs)
Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.
Filters Django provides some log filters in addition to those provided by the Python logging module.
class CallbackFilter(callback)
This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False. For instance, to filter out UnreadablePostError (raised when a user cancels an upload) from the admin emails, you would create a filter function: from django.http import UnreadablePostError
def skip_unreadable_post(record):
if record.exc_info:
exc_type, exc_value = record.exc_info[:2]
if isinstance(exc_value, UnreadablePostError):
return False
return True
and then add it to your logging config: 'filters': {
'skip_unreadable_posts': {
'()': 'django.utils.log.CallbackFilter',
'callback': skip_unreadable_post,
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['skip_unreadable_posts'],
'class': 'django.utils.log.AdminEmailHandler',
},
},
class RequireDebugFalse
This filter will only pass on records when settings.DEBUG is False. This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False: 'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
},
},
class RequireDebugTrue
This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True. | django.ref.logging |
Logging See also How to configure and use logging Django logging reference Python programmers will often use print() in their code as a quick and convenient debugging tool. Using the logging framework is only a little more effort than that, but it’s much more elegant and flexible. As well as being useful for debugging, logging can also provide you with more - and better structured - information about the state and health of your application. Overview Django uses and extends Python’s builtin logging module to perform system logging. This module is discussed in detail in Python’s own documentation; this section provides a quick overview. The cast of players A Python logging configuration consists of four parts: Loggers Handlers Filters Formatters Loggers A logger is the entry point into the logging system. Each logger is a named bucket to which messages can be written for processing. A logger is configured to have a log level. This log level describes the severity of the messages that the logger will handle. Python defines the following log levels:
DEBUG: Low level system information for debugging purposes
INFO: General system information
WARNING: Information describing a minor problem that has occurred.
ERROR: Information describing a major problem that has occurred.
CRITICAL: Information describing a critical problem that has occurred. Each message that is written to the logger is a Log Record. Each log record also has a log level indicating the severity of that specific message. A log record can also contain useful metadata that describes the event that is being logged. This can include details such as a stack trace or an error code. When a message is given to the logger, the log level of the message is compared to the log level of the logger. If the log level of the message meets or exceeds the log level of the logger itself, the message will undergo further processing. If it doesn’t, the message will be ignored. Once a logger has determined that a message needs to be processed, it is passed to a Handler. Handlers The handler is the engine that determines what happens to each message in a logger. It describes a particular logging behavior, such as writing a message to the screen, to a file, or to a network socket. Like loggers, handlers also have a log level. If the log level of a log record doesn’t meet or exceed the level of the handler, the handler will ignore the message. A logger can have multiple handlers, and each handler can have a different log level. In this way, it is possible to provide different forms of notification depending on the importance of a message. For example, you could install one handler that forwards ERROR and CRITICAL messages to a paging service, while a second handler logs all messages (including ERROR and CRITICAL messages) to a file for later analysis. Filters A filter is used to provide additional control over which log records are passed from logger to handler. By default, any log message that meets log level requirements will be handled. However, by installing a filter, you can place additional criteria on the logging process. For example, you could install a filter that only allows ERROR messages from a particular source to be emitted. Filters can also be used to modify the logging record prior to being emitted. For example, you could write a filter that downgrades ERROR log records to WARNING records if a particular set of criteria are met. Filters can be installed on loggers or on handlers; multiple filters can be used in a chain to perform multiple filtering actions. Formatters Ultimately, a log record needs to be rendered as text. Formatters describe the exact format of that text. A formatter usually consists of a Python formatting string containing LogRecord attributes; however, you can also write custom formatters to implement specific formatting behavior. Security implications The logging system handles potentially sensitive information. For example, the log record may contain information about a web request or a stack trace, while some of the data you collect in your own loggers may also have security implications. You need to be sure you know: what information is collected where it will subsequently be stored how it will be transferred who might have access to it. To help control the collection of sensitive information, you can explicitly designate certain sensitive information to be filtered out of error reports – read more about how to filter error reports. AdminEmailHandler The built-in AdminEmailHandler deserves a mention in the context of security. If its include_html option is enabled, the email message it sends will contain a full traceback, with names and values of local variables at each level of the stack, plus the values of your Django settings (in other words, the same level of detail that is exposed in a web page when DEBUG is True). It’s generally not considered a good idea to send such potentially sensitive information over email. Consider instead using one of the many third-party services to which detailed logs can be sent to get the best of multiple worlds – the rich information of full tracebacks, clear management of who is notified and has access to the information, and so on. Configuring logging Python’s logging library provides several techniques to configure logging, ranging from a programmatic interface to configuration files. By default, Django uses the dictConfig format. In order to configure logging, you use LOGGING to define a dictionary of logging settings. These settings describe the loggers, handlers, filters and formatters that you want in your logging setup, and the log levels and other properties that you want those components to have. By default, the LOGGING setting is merged with Django’s default logging configuration using the following scheme. If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the dictConfig default if the key is missing) then all loggers from the default configuration will be disabled. Disabled loggers are not the same as removed; the logger will still exist, but will silently discard anything logged to it, not even propagating entries to a parent logger. Thus you should be very careful using 'disable_existing_loggers': True; it’s probably not what you want. Instead, you can set disable_existing_loggers to False and redefine some or all of the default loggers; or you can set LOGGING_CONFIG to None and handle logging config yourself. Logging is configured as part of the general Django setup() function. Therefore, you can be certain that loggers are always ready for use in your project code. Examples The full documentation for dictConfig format is the best source of information about logging configuration dictionaries. However, to give you a taste of what is possible, here are several examples. To begin, here’s a small configuration that will allow you to output all log messages to the console: settings.py import os
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
This configures the parent root logger to send messages with the WARNING level and higher to the console handler. By adjusting the level to INFO or DEBUG you can display more messages. This may be useful during development. Next we can add more fine-grained logging. Here’s an example of how to make the logging system print more messages from just the django named logger: settings.py import os
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
'propagate': False,
},
},
}
By default, this config sends messages from the django logger of level INFO or higher to the console. This is the same level as Django’s default logging config, except that the default config only displays log records when DEBUG=True. Django does not log many such INFO level messages. With this config, however, you can also set the environment variable DJANGO_LOG_LEVEL=DEBUG to see all of Django’s debug logging which is very verbose as it includes all database queries. You don’t have to log to the console. Here’s a configuration which writes all logging from the django named logger to a local file: settings.py LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/path/to/django/debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
If you use this example, be sure to change the 'filename' path to a location that’s writable by the user that’s running the Django application. Finally, here’s an example of a fairly complex logging setup: settings.py LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'filters': {
'special': {
'()': 'project.logging.SpecialFilter',
'foo': 'bar',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
}
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'myproject.custom': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'filters': ['special']
}
}
}
This logging configuration does the following things: Identifies the configuration as being in ‘dictConfig version 1’ format. At present, this is the only dictConfig format version.
Defines two formatters:
simple, that outputs the log level name (e.g., DEBUG) and the log message. The format string is a normal Python formatting string describing the details that are to be output on each logging line. The full list of detail that can be output can be found in Formatter Objects.
verbose, that outputs the log level name, the log message, plus the time, process, thread and module that generate the log message.
Defines two filters:
project.logging.SpecialFilter, using the alias special. If this filter required additional arguments, they can be provided as additional keys in the filter configuration dictionary. In this case, the argument foo will be given a value of bar when instantiating SpecialFilter.
django.utils.log.RequireDebugTrue, which passes on records when DEBUG is True.
Defines two handlers:
console, a StreamHandler, which prints any INFO (or higher) message to sys.stderr. This handler uses the simple output format.
mail_admins, an AdminEmailHandler, which emails any ERROR (or higher) message to the site ADMINS. This handler uses the special filter.
Configures three loggers:
django, which passes all messages to the console handler.
django.request, which passes all ERROR messages to the mail_admins handler. In addition, this logger is marked to not propagate messages. This means that log messages written to django.request will not be handled by the django logger.
myproject.custom, which passes all messages at INFO or higher that also pass the special filter to two handlers – the console, and mail_admins. This means that all INFO level messages (or higher) will be printed to the console; ERROR and CRITICAL messages will also be output via email. Custom logging configuration If you don’t want to use Python’s dictConfig format to configure your logger, you can specify your own configuration scheme. The LOGGING_CONFIG setting defines the callable that will be used to configure Django’s loggers. By default, it points at Python’s logging.config.dictConfig() function. However, if you want to use a different configuration process, you can use any other callable that takes a single argument. The contents of LOGGING will be provided as the value of that argument when logging is configured. Disabling logging configuration If you don’t want to configure logging at all (or you want to manually configure logging using your own approach), you can set LOGGING_CONFIG to None. This will disable the configuration process for Django’s default logging. Setting LOGGING_CONFIG to None only means that the automatic configuration process is disabled, not logging itself. If you disable the configuration process, Django will still make logging calls, falling back to whatever default logging behavior is defined. Here’s an example that disables Django’s logging configuration and then manually configures logging: settings.py LOGGING_CONFIG = None
import logging.config
logging.config.dictConfig(...)
Note that the default configuration process only calls LOGGING_CONFIG once settings are fully-loaded. In contrast, manually configuring the logging in your settings file will load your logging config immediately. As such, your logging config must appear after any settings on which it depends. | django.topics.logging |
Managers
class Manager
A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. The way Manager classes work is documented in Making queries; this document specifically touches on model options that customize Manager behavior. Manager names By default, Django adds a Manager with the name objects to every Django model class. However, if you want to use objects as a field name, or if you want to use a name other than objects for the Manager, you can rename it on a per-model basis. To rename the Manager for a given class, define a class attribute of type models.Manager() on that model. For example: from django.db import models
class Person(models.Model):
#...
people = models.Manager()
Using this example model, Person.objects will generate an AttributeError exception, but Person.people.all() will provide a list of all Person objects. Custom managers You can use a custom Manager in a particular model by extending the base Manager class and instantiating your custom Manager in your model. There are two reasons you might want to customize a Manager: to add extra Manager methods, and/or to modify the initial QuerySet the Manager returns. Adding extra manager methods Adding extra Manager methods is the preferred way to add “table-level” functionality to your models. (For “row-level” functionality – i.e., functions that act on a single instance of a model object – use Model methods, not custom Manager methods.) For example, this custom Manager adds a method with_counts(): from django.db import models
from django.db.models.functions import Coalesce
class PollManager(models.Manager):
def with_counts(self):
return self.annotate(
num_responses=Coalesce(models.Count("response"), 0)
)
class OpinionPoll(models.Model):
question = models.CharField(max_length=200)
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
# ...
With this example, you’d use OpinionPoll.objects.with_counts() to get a QuerySet of OpinionPoll objects with the extra num_responses attribute attached. A custom Manager method can return anything you want. It doesn’t have to return a QuerySet. Another thing to note is that Manager methods can access self.model to get the model class to which they’re attached. Modifying a manager’s initial QuerySet
A Manager’s base QuerySet returns all objects in the system. For example, using this model: from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
…the statement Book.objects.all() will return all books in the database. You can override a Manager’s base QuerySet by overriding the Manager.get_queryset() method. get_queryset() should return a QuerySet with the properties you require. For example, the following model has two Managers – one that returns all objects, and one that returns only the books by Roald Dahl: # First, define the Manager subclass.
class DahlBookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(author='Roald Dahl')
# Then hook it into the Book model explicitly.
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager() # The default manager.
dahl_objects = DahlBookManager() # The Dahl-specific manager.
With this sample model, Book.objects.all() will return all books in the database, but Book.dahl_objects.all() will only return the ones written by Roald Dahl. Because get_queryset() returns a QuerySet object, you can use filter(), exclude() and all the other QuerySet methods on it. So these statements are all legal: Book.dahl_objects.all()
Book.dahl_objects.filter(title='Matilda')
Book.dahl_objects.count()
This example also pointed out another interesting technique: using multiple managers on the same model. You can attach as many Manager() instances to a model as you’d like. This is a non-repetitive way to define common “filters” for your models. For example: class AuthorManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(role='A')
class EditorManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(role='E')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])
people = models.Manager()
authors = AuthorManager()
editors = EditorManager()
This example allows you to request Person.authors.all(), Person.editors.all(), and Person.people.all(), yielding predictable results. Default managers
Model._default_manager
If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects you’d like to work with. You can specify a custom default manager using Meta.default_manager_name. If you’re writing some code that must handle an unknown model, for example, in a third-party app that implements a generic view, use this manager (or _base_manager) rather than assuming the model has an objects manager. Base managers
Model._base_manager
Using managers for related object access By default, Django uses an instance of the Model._base_manager manager class when accessing related objects (i.e. choice.question), not the _default_manager on the related object. This is because Django needs to be able to retrieve the related object, even if it would otherwise be filtered out (and hence be inaccessible) by the default manager. If the normal base manager class (django.db.models.Manager) isn’t appropriate for your circumstances, you can tell Django which class to use by setting Meta.base_manager_name. Base managers aren’t used when querying on related models, or when accessing a one-to-many or many-to-many relationship. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions. Don’t filter away any results in this type of manager subclass This manager is used to access objects that are related to from some other model. In those situations, Django has to be able to see all the objects for the model it is fetching, so that anything which is referred to can be retrieved. Therefore, you should not override get_queryset() to filter out any rows. If you do so, Django will return incomplete results. Calling custom QuerySet methods from the manager While most methods from the standard QuerySet are accessible directly from the Manager, this is only the case for the extra methods defined on a custom QuerySet if you also implement them on the Manager: class PersonQuerySet(models.QuerySet):
def authors(self):
return self.filter(role='A')
def editors(self):
return self.filter(role='E')
class PersonManager(models.Manager):
def get_queryset(self):
return PersonQuerySet(self.model, using=self._db)
def authors(self):
return self.get_queryset().authors()
def editors(self):
return self.get_queryset().editors()
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])
people = PersonManager()
This example allows you to call both authors() and editors() directly from the manager Person.people. Creating a manager with QuerySet methods In lieu of the above approach which requires duplicating methods on both the QuerySet and the Manager, QuerySet.as_manager() can be used to create an instance of Manager with a copy of a custom QuerySet’s methods: class Person(models.Model):
...
people = PersonQuerySet.as_manager()
The Manager instance created by QuerySet.as_manager() will be virtually identical to the PersonManager from the previous example. Not every QuerySet method makes sense at the Manager level; for instance we intentionally prevent the QuerySet.delete() method from being copied onto the Manager class. Methods are copied according to the following rules: Public methods are copied by default. Private methods (starting with an underscore) are not copied by default. Methods with a queryset_only attribute set to False are always copied. Methods with a queryset_only attribute set to True are never copied. For example: class CustomQuerySet(models.QuerySet):
# Available on both Manager and QuerySet.
def public_method(self):
return
# Available only on QuerySet.
def _private_method(self):
return
# Available only on QuerySet.
def opted_out_public_method(self):
return
opted_out_public_method.queryset_only = True
# Available on both Manager and QuerySet.
def _opted_in_private_method(self):
return
_opted_in_private_method.queryset_only = False
from_queryset()
classmethod from_queryset(queryset_class)
For advanced usage you might want both a custom Manager and a custom QuerySet. You can do that by calling Manager.from_queryset() which returns a subclass of your base Manager with a copy of the custom QuerySet methods: class CustomManager(models.Manager):
def manager_only_method(self):
return
class CustomQuerySet(models.QuerySet):
def manager_and_queryset_method(self):
return
class MyModel(models.Model):
objects = CustomManager.from_queryset(CustomQuerySet)()
You may also store the generated class into a variable: MyManager = CustomManager.from_queryset(CustomQuerySet)
class MyModel(models.Model):
objects = MyManager()
Custom managers and model inheritance Here’s how Django handles custom managers and model inheritance: Managers from base classes are always inherited by the child class, using Python’s normal name resolution order (names on the child class override all others; then come names on the first parent class, and so on). If no managers are declared on a model and/or its parents, Django automatically creates the objects manager. The default manager on a class is either the one chosen with Meta.default_manager_name, or the first manager declared on the model, or the default manager of the first parent model. These rules provide the necessary flexibility if you want to install a collection of custom managers on a group of models, via an abstract base class, but still customize the default manager. For example, suppose you have this base class: class AbstractBase(models.Model):
# ...
objects = CustomManager()
class Meta:
abstract = True
If you use this directly in a subclass, objects will be the default manager if you declare no managers in the base class: class ChildA(AbstractBase):
# ...
# This class has CustomManager as the default manager.
pass
If you want to inherit from AbstractBase, but provide a different default manager, you can provide the default manager on the child class: class ChildB(AbstractBase):
# ...
# An explicit default manager.
default_manager = OtherManager()
Here, default_manager is the default. The objects manager is still available, since it’s inherited, but isn’t used as the default. Finally for this example, suppose you want to add extra managers to the child class, but still use the default from AbstractBase. You can’t add the new manager directly in the child class, as that would override the default and you would have to also explicitly include all the managers from the abstract base class. The solution is to put the extra managers in another base class and introduce it into the inheritance hierarchy after the defaults: class ExtraManager(models.Model):
extra_manager = OtherManager()
class Meta:
abstract = True
class ChildC(AbstractBase, ExtraManager):
# ...
# Default manager is CustomManager, but OtherManager is
# also available via the "extra_manager" attribute.
pass
Note that while you can define a custom manager on the abstract model, you can’t invoke any methods using the abstract model. That is: ClassA.objects.do_something()
is legal, but: AbstractBase.objects.do_something()
will raise an exception. This is because managers are intended to encapsulate logic for managing collections of objects. Since you can’t have a collection of abstract objects, it doesn’t make sense to be managing them. If you have functionality that applies to the abstract model, you should put that functionality in a staticmethod or classmethod on the abstract model. Implementation concerns Whatever features you add to your custom Manager, it must be possible to make a shallow copy of a Manager instance; i.e., the following code must work: >>> import copy
>>> manager = MyManager()
>>> my_copy = copy.copy(manager)
Django makes shallow copies of manager objects during certain queries; if your Manager cannot be copied, those queries will fail. This won’t be an issue for most custom managers. If you are just adding simple methods to your Manager, it is unlikely that you will inadvertently make instances of your Manager uncopyable. However, if you’re overriding __getattr__ or some other private method of your Manager object that controls object state, you should ensure that you don’t affect the ability of your Manager to be copied. | django.topics.db.managers |
add_message(request, level, message, extra_tags='', fail_silently=False) | django.ref.contrib.messages#django.contrib.messages.add_message |
get_messages(request) | django.ref.contrib.messages#django.contrib.messages.get_messages |
class MessageMiddleware | django.ref.middleware#django.contrib.messages.middleware.MessageMiddleware |
class storage.base.BaseStorage | django.ref.contrib.messages#django.contrib.messages.storage.base.BaseStorage |
class storage.base.Message
When you loop over the list of messages in a template, what you get are instances of the Message class. They have only a few attributes:
message: The actual text of the message.
level: An integer describing the type of the message (see the message levels section above).
tags: A string combining all the message’s tags (extra_tags and level_tag) separated by spaces.
extra_tags: A string containing custom tags for this message, separated by spaces. It’s empty by default.
level_tag: The string representation of the level. By default, it’s the lowercase version of the name of the associated constant, but this can be changed if you need by using the MESSAGE_TAGS setting. | django.ref.contrib.messages#django.contrib.messages.storage.base.Message |
class storage.cookie.CookieStorage
This class stores the message data in a cookie (signed with a secret hash to prevent manipulation) to persist notifications across requests. Old messages are dropped if the cookie data size would exceed 2048 bytes. Changed in Django 3.2: Messages format was changed to the RFC 6265 compliant format. | django.ref.contrib.messages#django.contrib.messages.storage.cookie.CookieStorage |
class storage.fallback.FallbackStorage
This class first uses CookieStorage, and falls back to using SessionStorage for the messages that could not fit in a single cookie. It also requires Django’s contrib.sessions application. This behavior avoids writing to the session whenever possible. It should provide the best performance in the general case. | django.ref.contrib.messages#django.contrib.messages.storage.fallback.FallbackStorage |
class storage.session.SessionStorage
This class stores all messages inside of the request’s session. Therefore it requires Django’s contrib.sessions application. | django.ref.contrib.messages#django.contrib.messages.storage.session.SessionStorage |
class views.SuccessMessageMixin
Adds a success message attribute to FormView based classes
get_success_message(cleaned_data)
cleaned_data is the cleaned data from the form which is used for string formatting | django.ref.contrib.messages#django.contrib.messages.views.SuccessMessageMixin |
get_success_message(cleaned_data)
cleaned_data is the cleaned data from the form which is used for string formatting | django.ref.contrib.messages#django.contrib.messages.views.SuccessMessageMixin.get_success_message |
Middleware This document explains all middleware components that come with Django. For information on how to use them and how to write your own middleware, see the middleware usage guide. Available middleware Cache middleware
class UpdateCacheMiddleware
class FetchFromCacheMiddleware
Enable the site-wide cache. If these are enabled, each Django-powered page will be cached for as long as the CACHE_MIDDLEWARE_SECONDS setting defines. See the cache documentation. “Common” middleware
class CommonMiddleware
Adds a few conveniences for perfectionists: Forbids access to user agents in the DISALLOWED_USER_AGENTS setting, which should be a list of compiled regular expression objects.
Performs URL rewriting based on the APPEND_SLASH and PREPEND_WWW settings. If APPEND_SLASH is True and the initial URL doesn’t end with a slash, and it is not found in the URLconf, then a new URL is formed by appending a slash at the end. If this new URL is found in the URLconf, then Django redirects the request to this new URL. Otherwise, the initial URL is processed as usual. For example, foo.com/bar will be redirected to foo.com/bar/ if you don’t have a valid URL pattern for foo.com/bar but do have a valid pattern for foo.com/bar/. If PREPEND_WWW is True, URLs that lack a leading “www.” will be redirected to the same URL with a leading “www.” Both of these options are meant to normalize URLs. The philosophy is that each URL should exist in one, and only one, place. Technically a URL foo.com/bar is distinct from foo.com/bar/ – a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs. If necessary, individual views may be excluded from the APPEND_SLASH behavior using the no_append_slash() decorator: from django.views.decorators.common import no_append_slash
@no_append_slash
def sensitive_fbv(request, *args, **kwargs):
"""View to be excluded from APPEND_SLASH."""
return HttpResponse()
Changed in Django 3.2: Support for the no_append_slash() decorator was added. Sets the Content-Length header for non-streaming responses.
CommonMiddleware.response_redirect_class
Defaults to HttpResponsePermanentRedirect. Subclass CommonMiddleware and override the attribute to customize the redirects issued by the middleware.
class BrokenLinkEmailsMiddleware
Sends broken link notification emails to MANAGERS (see How to manage error reporting). GZip middleware
class GZipMiddleware
Warning Security researchers recently revealed that when compression techniques (including GZipMiddleware) are used on a website, the site may become exposed to a number of possible attacks. Before using GZipMiddleware on your site, you should consider very carefully whether you are subject to these attacks. If you’re in any doubt about whether you’re affected, you should avoid using GZipMiddleware. For more details, see the the BREACH paper (PDF) and breachattack.com. The django.middleware.gzip.GZipMiddleware compresses content for browsers that understand GZip compression (all modern browsers). This middleware should be placed before any other middleware that need to read or write the response body so that compression happens afterward. It will NOT compress content if any of the following are true: The content body is less than 200 bytes long. The response has already set the Content-Encoding header. The request (the browser) hasn’t sent an Accept-Encoding header containing gzip. If the response has an ETag header, the ETag is made weak to comply with RFC 7232#section-2.1. You can apply GZip compression to individual views using the gzip_page() decorator. Conditional GET middleware
class ConditionalGetMiddleware
Handles conditional GET operations. If the response doesn’t have an ETag header, the middleware adds one if needed. If the response has an ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpResponseNotModified. Locale middleware
class LocaleMiddleware
Enables language selection based on data from the request. It customizes content for each user. See the internationalization documentation.
LocaleMiddleware.response_redirect_class
Defaults to HttpResponseRedirect. Subclass LocaleMiddleware and override the attribute to customize the redirects issued by the middleware. Message middleware
class MessageMiddleware
Enables cookie- and session-based message support. See the messages documentation. Security middleware Warning If your deployment situation allows, it’s usually a good idea to have your front-end web server perform the functionality provided by the SecurityMiddleware. That way, if there are requests that aren’t served by Django (such as static media or user-uploaded files), they will have the same protections as requests to your Django application.
class SecurityMiddleware
The django.middleware.security.SecurityMiddleware provides several security enhancements to the request/response cycle. Each one can be independently enabled or disabled with a setting. SECURE_CONTENT_TYPE_NOSNIFF SECURE_CROSS_ORIGIN_OPENER_POLICY SECURE_HSTS_INCLUDE_SUBDOMAINS SECURE_HSTS_PRELOAD SECURE_HSTS_SECONDS SECURE_REDIRECT_EXEMPT SECURE_REFERRER_POLICY SECURE_SSL_HOST SECURE_SSL_REDIRECT HTTP Strict Transport Security For sites that should only be accessed over HTTPS, you can instruct modern browsers to refuse to connect to your domain name via an insecure connection (for a given period of time) by setting the “Strict-Transport-Security” header. This reduces your exposure to some SSL-stripping man-in-the-middle (MITM) attacks. SecurityMiddleware will set this header for you on all HTTPS responses if you set the SECURE_HSTS_SECONDS setting to a non-zero integer value. When enabling HSTS, it’s a good idea to first use a small value for testing, for example, SECURE_HSTS_SECONDS = 3600 for one hour. Each time a web browser sees the HSTS header from your site, it will refuse to communicate non-securely (using HTTP) with your domain for the given period of time. Once you confirm that all assets are served securely on your site (i.e. HSTS didn’t break anything), it’s a good idea to increase this value so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year, is common). Additionally, if you set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True, SecurityMiddleware will add the includeSubDomains directive to the Strict-Transport-Security header. This is recommended (assuming all subdomains are served exclusively using HTTPS), otherwise your site may still be vulnerable via an insecure connection to a subdomain. If you wish to submit your site to the browser preload list, set the SECURE_HSTS_PRELOAD setting to True. That appends the preload directive to the Strict-Transport-Security header. Warning The HSTS policy applies to your entire domain, not just the URL of the response that you set the header on. Therefore, you should only use it if your entire domain is served via HTTPS only. Browsers properly respecting the HSTS header will refuse to allow users to bypass warnings and connect to a site with an expired, self-signed, or otherwise invalid SSL certificate. If you use HSTS, make sure your certificates are in good shape and stay that way! Note If you are deployed behind a load-balancer or reverse-proxy server, and the Strict-Transport-Security header is not being added to your responses, it may be because Django doesn’t realize that it’s on a secure connection; you may need to set the SECURE_PROXY_SSL_HEADER setting. Referrer Policy Browsers use the Referer header as a way to send information to a site about how users got there. When a user clicks a link, the browser will send the full URL of the linking page as the referrer. While this can be useful for some purposes – like figuring out who’s linking to your site – it also can cause privacy concerns by informing one site that a user was visiting another site. Some browsers have the ability to accept hints about whether they should send the HTTP Referer header when a user clicks a link; this hint is provided via the Referrer-Policy header. This header can suggest any of three behaviors to browsers: Full URL: send the entire URL in the Referer header. For example, if the user is visiting https://example.com/page.html, the Referer header would contain "https://example.com/page.html". Origin only: send only the “origin” in the referrer. The origin consists of the scheme, host and (optionally) port number. For example, if the user is visiting https://example.com/page.html, the origin would be https://example.com/. No referrer: do not send a Referer header at all. There are two types of conditions this header can tell a browser to watch out for: Same-origin versus cross-origin: a link from https://example.com/1.html to https://example.com/2.html is same-origin. A link from https://example.com/page.html to https://not.example.com/page.html is cross-origin. Protocol downgrade: a downgrade occurs if the page containing the link is served via HTTPS, but the page being linked to is not served via HTTPS. Warning When your site is served via HTTPS, Django’s CSRF protection system requires the Referer header to be present, so completely disabling the Referer header will interfere with CSRF protection. To gain most of the benefits of disabling Referer headers while also keeping CSRF protection, consider enabling only same-origin referrers. SecurityMiddleware can set the Referrer-Policy header for you, based on the SECURE_REFERRER_POLICY setting (note spelling: browsers send a Referer header when a user clicks a link, but the header instructing a browser whether to do so is spelled Referrer-Policy). The valid values for this setting are:
no-referrer Instructs the browser to send no referrer for links clicked on this site.
no-referrer-when-downgrade Instructs the browser to send a full URL as the referrer, but only when no protocol downgrade occurs.
origin Instructs the browser to send only the origin, not the full URL, as the referrer.
origin-when-cross-origin Instructs the browser to send the full URL as the referrer for same-origin links, and only the origin for cross-origin links.
same-origin Instructs the browser to send a full URL, but only for same-origin links. No referrer will be sent for cross-origin links.
strict-origin Instructs the browser to send only the origin, not the full URL, and to send no referrer when a protocol downgrade occurs.
strict-origin-when-cross-origin Instructs the browser to send the full URL when the link is same-origin and no protocol downgrade occurs; send only the origin when the link is cross-origin and no protocol downgrade occurs; and no referrer when a protocol downgrade occurs.
unsafe-url Instructs the browser to always send the full URL as the referrer. Unknown Policy Values Where a policy value is unknown by a user agent, it is possible to specify multiple policy values to provide a fallback. The last specified value that is understood takes precedence. To support this, an iterable or comma-separated string can be used with SECURE_REFERRER_POLICY. Cross-Origin Opener Policy New in Django 4.0. Some browsers have the ability to isolate top-level windows from other documents by putting them in a separate browsing context group based on the value of the Cross-Origin Opener Policy (COOP) header. If a document that is isolated in this way opens a cross-origin popup window, the popup’s window.opener property will be null. Isolating windows using COOP is a defense-in-depth protection against cross-origin attacks, especially those like Spectre which allowed exfiltration of data loaded into a shared browsing context. SecurityMiddleware can set the Cross-Origin-Opener-Policy header for you, based on the SECURE_CROSS_ORIGIN_OPENER_POLICY setting. The valid values for this setting are:
same-origin Isolates the browsing context exclusively to same-origin documents. Cross-origin documents are not loaded in the same browsing context. This is the default and most secure option.
same-origin-allow-popups Isolates the browsing context to same-origin documents or those which either don’t set COOP or which opt out of isolation by setting a COOP of unsafe-none.
unsafe-none Allows the document to be added to its opener’s browsing context group unless the opener itself has a COOP of same-origin or same-origin-allow-popups. X-Content-Type-Options: nosniff Some browsers will try to guess the content types of the assets that they fetch, overriding the Content-Type header. While this can help display sites with improperly configured servers, it can also pose a security risk. If your site serves user-uploaded files, a malicious user could upload a specially-crafted file that would be interpreted as HTML or JavaScript by the browser when you expected it to be something harmless. To prevent the browser from guessing the content type and force it to always use the type provided in the Content-Type header, you can pass the X-Content-Type-Options: nosniff header. SecurityMiddleware will do this for all responses if the SECURE_CONTENT_TYPE_NOSNIFF setting is True. Note that in most deployment situations where Django isn’t involved in serving user-uploaded files, this setting won’t help you. For example, if your MEDIA_URL is served directly by your front-end web server (nginx, Apache, etc.) then you’d want to set this header there. On the other hand, if you are using Django to do something like require authorization in order to download files and you cannot set the header using your web server, this setting will be useful. SSL Redirect If your site offers both HTTP and HTTPS connections, most users will end up with an unsecured connection by default. For best security, you should redirect all HTTP connections to HTTPS. If you set the SECURE_SSL_REDIRECT setting to True, SecurityMiddleware will permanently (HTTP 301) redirect all HTTP connections to HTTPS. Note For performance reasons, it’s preferable to do these redirects outside of Django, in a front-end load balancer or reverse-proxy server such as nginx. SECURE_SSL_REDIRECT is intended for the deployment situations where this isn’t an option. If the SECURE_SSL_HOST setting has a value, all redirects will be sent to that host instead of the originally-requested host. If there are a few pages on your site that should be available over HTTP, and not redirected to HTTPS, you can list regular expressions to match those URLs in the SECURE_REDIRECT_EXEMPT setting. Note If you are deployed behind a load-balancer or reverse-proxy server and Django can’t seem to tell when a request actually is already secure, you may need to set the SECURE_PROXY_SSL_HEADER setting. Session middleware
class SessionMiddleware
Enables session support. See the session documentation. Site middleware
class CurrentSiteMiddleware
Adds the site attribute representing the current site to every incoming HttpRequest object. See the sites documentation. Authentication middleware
class AuthenticationMiddleware
Adds the user attribute, representing the currently-logged-in user, to every incoming HttpRequest object. See Authentication in web requests.
class RemoteUserMiddleware
Middleware for utilizing web server provided authentication. See How to authenticate using REMOTE_USER for usage details.
class PersistentRemoteUserMiddleware
Middleware for utilizing web server provided authentication when enabled only on the login page. See Using REMOTE_USER on login pages only for usage details. CSRF protection middleware
class CsrfViewMiddleware
Adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value. See the Cross Site Request Forgery protection documentation.
X-Frame-Options middleware
class XFrameOptionsMiddleware
Simple clickjacking protection via the X-Frame-Options header. Middleware ordering Here are some hints about the ordering of various Django middleware classes:
SecurityMiddleware It should go near the top of the list if you’re going to turn on the SSL redirect as that avoids running through a bunch of other unnecessary middleware.
UpdateCacheMiddleware Before those that modify the Vary header (SessionMiddleware, GZipMiddleware, LocaleMiddleware).
GZipMiddleware Before any middleware that may change or use the response body. After UpdateCacheMiddleware: Modifies Vary header.
SessionMiddleware Before any middleware that may raise an exception to trigger an error view (such as PermissionDenied) if you’re using CSRF_USE_SESSIONS. After UpdateCacheMiddleware: Modifies Vary header.
ConditionalGetMiddleware Before any middleware that may change the response (it sets the ETag header). After GZipMiddleware so it won’t calculate an ETag header on gzipped contents.
LocaleMiddleware One of the topmost, after SessionMiddleware (uses session data) and UpdateCacheMiddleware (modifies Vary header).
CommonMiddleware Before any middleware that may change the response (it sets the Content-Length header). A middleware that appears before CommonMiddleware and changes the response must reset Content-Length. Close to the top: it redirects when APPEND_SLASH or PREPEND_WWW are set to True. After SessionMiddleware if you’re using CSRF_USE_SESSIONS.
CsrfViewMiddleware Before any view middleware that assumes that CSRF attacks have been dealt with. Before RemoteUserMiddleware, or any other authentication middleware that may perform a login, and hence rotate the CSRF token, before calling down the middleware chain. After SessionMiddleware if you’re using CSRF_USE_SESSIONS.
AuthenticationMiddleware After SessionMiddleware: uses session storage.
MessageMiddleware After SessionMiddleware: can use session-based storage.
FetchFromCacheMiddleware After any middleware that modifies the Vary header: that header is used to pick a value for the cache hash-key.
FlatpageFallbackMiddleware Should be near the bottom as it’s a last-resort type of middleware.
RedirectFallbackMiddleware Should be near the bottom as it’s a last-resort type of middleware. | django.ref.middleware |
Middleware Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware, that associates users with requests using sessions. This document explains how middleware works, how you activate middleware, and how to write your own middleware. Django ships with some built-in middleware you can use right out of the box. They’re documented in the built-in middleware reference. Writing your own middleware A middleware factory is a callable that takes a get_response callable and returns a middleware. A middleware is a callable that takes a request and returns a response, just like a view. A middleware can be written as a function that looks like this: def simple_middleware(get_response):
# One-time configuration and initialization.
def middleware(request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
return middleware
Or it can be written as a class whose instances are callable, like this: class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
The get_response callable provided by Django might be the actual view (if this is the last listed middleware) or it might be the next middleware in the chain. The current middleware doesn’t need to know or care what exactly it is, just that it represents whatever comes next. The above is a slight simplification – the get_response callable for the last middleware in the chain won’t be the actual view but rather a wrapper method from the handler which takes care of applying view middleware, calling the view with appropriate URL arguments, and applying template-response and exception middleware. Middleware can either support only synchronous Python (the default), only asynchronous Python, or both. See Asynchronous support for details of how to advertise what you support, and know what kind of request you are getting. Middleware can live anywhere on your Python path. __init__(get_response) Middleware factories must accept a get_response argument. You can also initialize some global state for the middleware. Keep in mind a couple of caveats: Django initializes your middleware with only the get_response argument, so you can’t define __init__() as requiring any other arguments. Unlike the __call__() method which is called once per request, __init__() is called only once, when the web server starts. Marking middleware as unused It’s sometimes useful to determine at startup time whether a piece of middleware should be used. In these cases, your middleware’s __init__() method may raise MiddlewareNotUsed. Django will then remove that middleware from the middleware process and log a debug message to the django.request logger when DEBUG is True. Activating middleware To activate a middleware component, add it to the MIDDLEWARE list in your Django settings. In MIDDLEWARE, each middleware component is represented by a string: the full Python path to the middleware factory’s class or function name. For example, here’s the default value created by django-admin
startproject: MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
A Django installation doesn’t require any middleware — MIDDLEWARE can be empty, if you’d like — but it’s strongly suggested that you at least use CommonMiddleware. The order in MIDDLEWARE matters because a middleware can depend on other middleware. For instance, AuthenticationMiddleware stores the authenticated user in the session; therefore, it must run after SessionMiddleware. See Middleware ordering for some common hints about ordering of Django middleware classes. Middleware order and layering During the request phase, before calling the view, Django applies middleware in the order it’s defined in MIDDLEWARE, top-down. You can think of it like an onion: each middleware class is a “layer” that wraps the view, which is in the core of the onion. If the request passes through all the layers of the onion (each one calls get_response to pass the request in to the next layer), all the way to the view at the core, the response will then pass through every layer (in reverse order) on the way back out. If one of the layers decides to short-circuit and return a response without ever calling its get_response, none of the layers of the onion inside that layer (including the view) will see the request or the response. The response will only return through the same layers that the request passed in through. Other middleware hooks Besides the basic request/response middleware pattern described earlier, you can add three other special methods to class-based middleware: process_view()
process_view(request, view_func, view_args, view_kwargs)
request is an HttpRequest object. view_func is the Python function that Django is about to use. (It’s the actual function object, not the name of the function as a string.) view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view. Neither view_args nor view_kwargs include the first view argument (request). process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won’t bother calling the appropriate view; it’ll apply response middleware to that HttpResponse and return the result. Note Accessing request.POST inside middleware before the view runs or in process_view() will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided. The CsrfViewMiddleware class can be considered an exception, as it provides the csrf_exempt() and csrf_protect() decorators which allow views to explicitly control at what point the CSRF validation should occur. process_exception()
process_exception(request, exception)
request is an HttpRequest object. exception is an Exception object raised by the view function. Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied and the resulting response returned to the browser. Otherwise, default exception handling kicks in. Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the process_exception methods of the middleware classes above that middleware won’t be called at all. process_template_response()
process_template_response(request, response)
request is an HttpRequest object. response is the TemplateResponse object (or equivalent) returned by a Django view or by a middleware. process_template_response() is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent. It must return a response object that implements a render method. It could alter the given response by changing response.template_name and response.context_data, or it could create and return a brand-new TemplateResponse or equivalent. You don’t need to explicitly render responses – responses will be automatically rendered once all template response middleware has been called. Middleware are run in reverse order during the response phase, which includes process_template_response(). Dealing with streaming responses Unlike HttpResponse, StreamingHttpResponse does not have a content attribute. As a result, middleware can no longer assume that all responses will have a content attribute. If they need access to the content, they must test for streaming responses and adjust their behavior accordingly: if response.streaming:
response.streaming_content = wrap_streaming_content(response.streaming_content)
else:
response.content = alter_content(response.content)
Note streaming_content should be assumed to be too large to hold in memory. Response middleware may wrap it in a new generator, but must not consume it. Wrapping is typically implemented as follows: def wrap_streaming_content(content):
for chunk in content:
yield alter_content(chunk)
Exception handling Django automatically converts exceptions raised by the view or by middleware into an appropriate HTTP response with an error status code. Certain exceptions are converted to 4xx status codes, while an unknown exception is converted to a 500 status code. This conversion takes place before and after each middleware (you can think of it as the thin film in between each layer of the onion), so that every middleware can always rely on getting some kind of HTTP response back from calling its get_response callable. Middleware don’t need to worry about wrapping their call to get_response in a try/except and handling an exception that might have been raised by a later middleware or the view. Even if the very next middleware in the chain raises an Http404 exception, for example, your middleware won’t see that exception; instead it will get an HttpResponse object with a status_code of 404. You can set DEBUG_PROPAGATE_EXCEPTIONS to True to skip this conversion and propagate exceptions upward. Asynchronous support Middleware can support any combination of synchronous and asynchronous requests. Django will adapt requests to fit the middleware’s requirements if it cannot support both, but at a performance penalty. By default, Django assumes that your middleware is capable of handling only synchronous requests. To change these assumptions, set the following attributes on your middleware factory function or class:
sync_capable is a boolean indicating if the middleware can handle synchronous requests. Defaults to True.
async_capable is a boolean indicating if the middleware can handle asynchronous requests. Defaults to False. If your middleware has both sync_capable = True and async_capable = True, then Django will pass it the request without converting it. In this case, you can work out if your middleware will receive async requests by checking if the get_response object you are passed is a coroutine function, using asyncio.iscoroutinefunction(). The django.utils.decorators module contains sync_only_middleware(), async_only_middleware(), and sync_and_async_middleware() decorators that allow you to apply these flags to middleware factory functions. The returned callable must match the sync or async nature of the get_response method. If you have an asynchronous get_response, you must return a coroutine function (async def). process_view, process_template_response and process_exception methods, if they are provided, should also be adapted to match the sync/async mode. However, Django will individually adapt them as required if you do not, at an additional performance penalty. Here’s an example of how to create a middleware function that supports both: import asyncio
from django.utils.decorators import sync_and_async_middleware
@sync_and_async_middleware
def simple_middleware(get_response):
# One-time configuration and initialization goes here.
if asyncio.iscoroutinefunction(get_response):
async def middleware(request):
# Do something here!
response = await get_response(request)
return response
else:
def middleware(request):
# Do something here!
response = get_response(request)
return response
return middleware
Note If you declare a hybrid middleware that supports both synchronous and asynchronous calls, the kind of call you get may not match the underlying view. Django will optimize the middleware call stack to have as few sync/async transitions as possible. Thus, even if you are wrapping an async view, you may be called in sync mode if there is other, synchronous middleware between you and the view. Upgrading pre-Django 1.10-style middleware
class django.utils.deprecation.MiddlewareMixin
Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES, and support synchronous and asynchronous requests. All middleware classes included with Django are compatible with both settings. The mixin provides an __init__() method that requires a get_response argument and stores it in self.get_response. The __call__() method: Calls self.process_request(request) (if defined). Calls self.get_response(request) to get the response from later middleware and the view. Calls self.process_response(request, response) (if defined). Returns the response. If used with MIDDLEWARE_CLASSES, the __call__() method will never be used; Django calls process_request() and process_response() directly. In most cases, inheriting from this mixin will be sufficient to make an old-style middleware compatible with the new system with sufficient backwards-compatibility. The new short-circuiting semantics will be harmless or even beneficial to the existing middleware. In a few cases, a middleware class may need some changes to adjust to the new semantics. These are the behavioral differences between using MIDDLEWARE and MIDDLEWARE_CLASSES: Under MIDDLEWARE_CLASSES, every middleware will always have its process_response method called, even if an earlier middleware short-circuited by returning a response from its process_request method. Under MIDDLEWARE, middleware behaves more like an onion: the layers that a response goes through on the way out are the same layers that saw the request on the way in. If a middleware short-circuits, only that middleware and the ones before it in MIDDLEWARE will see the response. Under MIDDLEWARE_CLASSES, process_exception is applied to exceptions raised from a middleware process_request method. Under MIDDLEWARE, process_exception applies only to exceptions raised from the view (or from the render method of a TemplateResponse). Exceptions raised from a middleware are converted to the appropriate HTTP response and then passed to the next middleware. Under MIDDLEWARE_CLASSES, if a process_response method raises an exception, the process_response methods of all earlier middleware are skipped and a 500 Internal Server Error HTTP response is always returned (even if the exception raised was e.g. an Http404). Under MIDDLEWARE, an exception raised from a middleware will immediately be converted to the appropriate HTTP response, and then the next middleware in line will see that response. Middleware are never skipped due to a middleware raising an exception. | django.topics.http.middleware |
class FetchFromCacheMiddleware | django.ref.middleware#django.middleware.cache.FetchFromCacheMiddleware |
class UpdateCacheMiddleware | django.ref.middleware#django.middleware.cache.UpdateCacheMiddleware |
class XFrameOptionsMiddleware | django.ref.middleware#django.middleware.clickjacking.XFrameOptionsMiddleware |
class BrokenLinkEmailsMiddleware | django.ref.middleware#django.middleware.common.BrokenLinkEmailsMiddleware |
class CommonMiddleware | django.ref.middleware#django.middleware.common.CommonMiddleware |
CommonMiddleware.response_redirect_class | django.ref.middleware#django.middleware.common.CommonMiddleware.response_redirect_class |
class CsrfViewMiddleware | django.ref.middleware#django.middleware.csrf.CsrfViewMiddleware |
class GZipMiddleware | django.ref.middleware#django.middleware.gzip.GZipMiddleware |
class ConditionalGetMiddleware | django.ref.middleware#django.middleware.http.ConditionalGetMiddleware |
class LocaleMiddleware | django.ref.middleware#django.middleware.locale.LocaleMiddleware |
LocaleMiddleware.response_redirect_class | django.ref.middleware#django.middleware.locale.LocaleMiddleware.response_redirect_class |
class SecurityMiddleware | django.ref.middleware#django.middleware.security.SecurityMiddleware |
Migrations Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into. The Commands There are several commands which you will use to interact with migrations and Django’s handling of database schema:
migrate, which is responsible for applying and unapplying migrations.
makemigrations, which is responsible for creating new migrations based on the changes you have made to your models.
sqlmigrate, which displays the SQL statements for a migration.
showmigrations, which lists a project’s migrations and their status. You should think of migrations as a version control system for your database schema. makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database. The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed to, and distributed as part of, its codebase. You should be making them once on your development machine and then running the same migrations on your colleagues’ machines, your staging machines, and eventually your production machines. Note It is possible to override the name of the package which contains the migrations on a per-app basis by modifying the MIGRATION_MODULES setting. Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see in development and staging is, under the same circumstances, exactly what will happen in production. Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators). Backend Support Migrations are supported on all backends that Django ships with, as well as any third-party backends if they have programmed in support for schema alteration (done via the SchemaEditor class). However, some databases are more capable than others when it comes to schema migrations; some of the caveats are covered below. PostgreSQL PostgreSQL is the most capable of all the databases here in terms of schema support. The only caveat is that prior to PostgreSQL 11, adding columns with default values causes a full rewrite of the table, for a time proportional to its size. For this reason, it’s recommended you always create new columns with null=True, as this way they will be added immediately. MySQL MySQL lacks support for transactions around schema alteration operations, meaning that if a migration fails to apply you will have to manually unpick the changes in order to try again (it’s impossible to roll back to an earlier point). In addition, MySQL will fully rewrite tables for almost every schema operation and generally takes a time proportional to the number of rows in the table to add or remove columns. On slower hardware this can be worse than a minute per million rows - adding a few columns to a table with just a few million rows could lock your site up for over ten minutes. Finally, MySQL has relatively small limits on name lengths for columns, tables and indexes, as well as a limit on the combined size of all columns an index covers. This means that indexes that are possible on other backends will fail to be created under MySQL. SQLite SQLite has very little built-in schema alteration support, and so Django attempts to emulate it by: Creating a new table with the new schema Copying the data across Dropping the old table Renaming the new table to match the original name This process generally works well, but it can be slow and occasionally buggy. It is not recommended that you run and migrate SQLite in a production environment unless you are very aware of the risks and its limitations; the support Django ships with is designed to allow developers to use SQLite on their local machines to develop less complex Django projects without the need for a full database. Workflow Django can create migrations for you. Make changes to your models - say, add a field and remove a model - and then run makemigrations: $ python manage.py makemigrations
Migrations for 'books':
books/migrations/0003_auto.py:
- Alter field author on book
Your models will be scanned and compared to the versions currently contained in your migration files, and then a new set of migrations will be written out. Make sure to read the output to see what makemigrations thinks you have changed - it’s not perfect, and for complex changes it might not be detecting what you expect. Once you have your new migration files, you should apply them to your database to make sure they work as expected: $ python manage.py migrate
Operations to perform:
Apply all migrations: books
Running migrations:
Rendering model states... DONE
Applying books.0003_auto... OK
Once the migration is applied, commit the migration and the models change to your version control system as a single commit - that way, when other developers (or your production servers) check out the code, they’ll get both the changes to your models and the accompanying migration at the same time. If you want to give the migration(s) a meaningful name instead of a generated one, you can use the makemigrations --name option: $ python manage.py makemigrations --name changed_my_model your_app_label
Version control Because migrations are stored in version control, you’ll occasionally come across situations where you and another developer have both committed a migration to the same app at the same time, resulting in two migrations with the same number. Don’t worry - the numbers are just there for developers’ reference, Django just cares that each migration has a different name. Migrations specify which other migrations they depend on - including earlier migrations in the same app - in the file, so it’s possible to detect when there’s two new migrations for the same app that aren’t ordered. When this happens, Django will prompt you and give you some options. If it thinks it’s safe enough, it will offer to automatically linearize the two migrations for you. If not, you’ll have to go in and modify the migrations yourself - don’t worry, this isn’t difficult, and is explained more in Migration files below. Transactions On databases that support DDL transactions (SQLite and PostgreSQL), all migration operations will run inside a single transaction by default. In contrast, if a database doesn’t support DDL transactions (e.g. MySQL, Oracle) then all operations will run without a transaction. You can prevent a migration from running in a transaction by setting the atomic attribute to False. For example: from django.db import migrations
class Migration(migrations.Migration):
atomic = False
It’s also possible to execute parts of the migration inside a transaction using atomic() or by passing atomic=True to RunPython. See Non-atomic migrations for more details. Dependencies While migrations are per-app, the tables and relationships implied by your models are too complex to be created for one app at a time. When you make a migration that requires something else to run - for example, you add a ForeignKey in your books app to your authors app - the resulting migration will contain a dependency on a migration in authors. This means that when you run the migrations, the authors migration runs first and creates the table the ForeignKey references, and then the migration that makes the ForeignKey column runs afterward and creates the constraint. If this didn’t happen, the migration would try to create the ForeignKey column without the table it’s referencing existing and your database would throw an error. This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in makemigrations or migrate) is a best-efforts promise, and not a guarantee; any other apps that need to be used to get dependencies correct will be. Apps without migrations must not have relations (ForeignKey, ManyToManyField, etc.) to apps with migrations. Sometimes it may work, but it’s not supported. Migration files Migrations are stored as an on-disk format, referred to here as “migration files”. These files are actually normal Python files with an agreed-upon object layout, written in a declarative style. A basic migration file looks like this: from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('migrations', '0001_initial')]
operations = [
migrations.DeleteModel('Tribble'),
migrations.AddField('Author', 'rating', models.IntegerField(default=0)),
]
What Django looks for when it loads a migration file (as a Python module) is a subclass of django.db.migrations.Migration called Migration. It then inspects this object for four attributes, only two of which are used most of the time:
dependencies, a list of migrations this one depends on.
operations, a list of Operation classes that define what this migration does. The operations are the key; they are a set of declarative instructions which tell Django what schema changes need to be made. Django scans them and builds an in-memory representation of all of the schema changes to all apps, and uses this to generate the SQL which makes the schema changes. That in-memory structure is also used to work out what the differences are between your models and the current state of your migrations; Django runs through all the changes, in order, on an in-memory set of models to come up with the state of your models last time you ran makemigrations. It then uses these models to compare against the ones in your models.py files to work out what you have changed. You should rarely, if ever, need to edit migration files by hand, but it’s entirely possible to write them manually if you need to. Some of the more complex operations are not autodetectable and are only available via a hand-written migration, so don’t be scared about editing them if you have to. Custom fields You can’t modify the number of positional arguments in an already migrated custom field without raising a TypeError. The old migration will call the modified __init__ method with the old signature. So if you need a new argument, please create a keyword argument and add something like assert 'argument_name' in kwargs in the constructor. Model managers You can optionally serialize managers into migrations and have them available in RunPython operations. This is done by defining a use_in_migrations attribute on the manager class: class MyManager(models.Manager):
use_in_migrations = True
class MyModel(models.Model):
objects = MyManager()
If you are using the from_queryset() function to dynamically generate a manager class, you need to inherit from the generated class to make it importable: class MyManager(MyBaseManager.from_queryset(CustomQuerySet)):
use_in_migrations = True
class MyModel(models.Model):
objects = MyManager()
Please refer to the notes about Historical models in migrations to see the implications that come along. Initial migrations
Migration.initial
The “initial migrations” for an app are the migrations that create the first version of that app’s tables. Usually an app will have one initial migration, but in some cases of complex model interdependencies it may have two or more. Initial migrations are marked with an initial = True class attribute on the migration class. If an initial class attribute isn’t found, a migration will be considered “initial” if it is the first migration in the app (i.e. if it has no dependencies on any other migration in the same app). When the migrate --fake-initial option is used, these initial migrations are treated specially. For an initial migration that creates one or more tables (CreateModel operation), Django checks that all of those tables already exist in the database and fake-applies the migration if so. Similarly, for an initial migration that adds one or more fields (AddField operation), Django checks that all of the respective columns already exist in the database and fake-applies the migration if so. Without --fake-initial, initial migrations are treated no differently from any other migration. History consistency As previously discussed, you may need to linearize migrations manually when two development branches are joined. While editing migration dependencies, you can inadvertently create an inconsistent history state where a migration has been applied but some of its dependencies haven’t. This is a strong indication that the dependencies are incorrect, so Django will refuse to run migrations or make new migrations until it’s fixed. When using multiple databases, you can use the allow_migrate() method of database routers to control which databases makemigrations checks for consistent history. Adding migrations to apps New apps come preconfigured to accept migrations, and so you can add migrations by running makemigrations once you’ve made some changes. If your app already has models and database tables, and doesn’t have migrations yet (for example, you created it against a previous Django version), you’ll need to convert it to use migrations by running: $ python manage.py makemigrations your_app_label
This will make a new initial migration for your app. Now, run python
manage.py migrate --fake-initial, and Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied. (Without the migrate
--fake-initial flag, the command would error out because the tables it wants to create already exist.) Note that this only works given two things: You have not changed your models since you made their tables. For migrations to work, you must make the initial migration first and then make changes, as Django compares changes against migration files, not the database. You have not manually edited your database - Django won’t be able to detect that your database doesn’t match your models, you’ll just get errors when migrations try to modify those tables. Reversing migrations Migrations can be reversed with migrate by passing the number of the previous migration. For example, to reverse migration books.0003: $ python manage.py migrate books 0002
Operations to perform:
Target specific migration: 0002_auto, from books
Running migrations:
Rendering model states... DONE
Unapplying books.0003_auto... OK
...\> py manage.py migrate books 0002
Operations to perform:
Target specific migration: 0002_auto, from books
Running migrations:
Rendering model states... DONE
Unapplying books.0003_auto... OK
If you want to reverse all migrations applied for an app, use the name zero: $ python manage.py migrate books zero
Operations to perform:
Unapply all migrations: books
Running migrations:
Rendering model states... DONE
Unapplying books.0002_auto... OK
Unapplying books.0001_initial... OK
...\> py manage.py migrate books zero
Operations to perform:
Unapply all migrations: books
Running migrations:
Rendering model states... DONE
Unapplying books.0002_auto... OK
Unapplying books.0001_initial... OK
A migration is irreversible if it contains any irreversible operations. Attempting to reverse such migrations will raise IrreversibleError: $ python manage.py migrate books 0002
Operations to perform:
Target specific migration: 0002_auto, from books
Running migrations:
Rendering model states... DONE
Unapplying books.0003_auto...Traceback (most recent call last):
django.db.migrations.exceptions.IrreversibleError: Operation <RunSQL sql='DROP TABLE demo_books'> in books.0003_auto is not reversible
...\> py manage.py migrate books 0002
Operations to perform:
Target specific migration: 0002_auto, from books
Running migrations:
Rendering model states... DONE
Unapplying books.0003_auto...Traceback (most recent call last):
django.db.migrations.exceptions.IrreversibleError: Operation <RunSQL sql='DROP TABLE demo_books'> in books.0003_auto is not reversible
Historical models When you run migrations, Django is working from historical versions of your models stored in the migration files. If you write Python code using the RunPython operation, or if you have allow_migrate methods on your database routers, you need to use these historical model versions rather than importing them directly. Warning If you import models directly rather than using the historical models, your migrations may work initially but will fail in the future when you try to re-run old migrations (commonly, when you set up a new installation and run through all the migrations to set up the database). This means that historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes. Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones). Warning This means that you will NOT have custom save() methods called on objects when you access them in migrations, and you will NOT have any custom constructors or instance methods. Plan appropriately! References to functions in field options such as upload_to and limit_choices_to and model manager declarations with managers having use_in_migrations = True are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations. In addition, the concrete base classes of the model are stored as pointers, so you must always keep base classes around for as long as there is a migration that contains a reference to them. On the plus side, methods and managers from these base classes inherit normally, so if you absolutely need access to these you can opt to move them into a superclass. To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files. Considerations when removing model fields Similar to the “references to historical functions” considerations described in the previous section, removing custom model fields from your project or third-party app will cause a problem if they are referenced in old migrations. To help with this situation, Django provides some model field attributes to assist with model field deprecation using the system checks framework. Add the system_check_deprecated_details attribute to your model field similar to the following: class IPAddressField(Field):
system_check_deprecated_details = {
'msg': (
'IPAddressField has been deprecated. Support for it (except '
'in historical migrations) will be removed in Django 1.9.'
),
'hint': 'Use GenericIPAddressField instead.', # optional
'id': 'fields.W900', # pick a unique ID for your field.
}
After a deprecation period of your choosing (two or three feature releases for fields in Django itself), change the system_check_deprecated_details attribute to system_check_removed_details and update the dictionary similar to: class IPAddressField(Field):
system_check_removed_details = {
'msg': (
'IPAddressField has been removed except for support in '
'historical migrations.'
),
'hint': 'Use GenericIPAddressField instead.',
'id': 'fields.E900', # pick a unique ID for your field.
}
You should keep the field’s methods that are required for it to operate in database migrations such as __init__(), deconstruct(), and get_internal_type(). Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely. Data Migrations As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want. Migrations that alter data are usually called “data migrations”; they’re best written as separate migrations, sitting alongside your schema migrations. Django can’t automatically generate data migrations for you, as it does with schema migrations, but it’s not very hard to write them. Migration files in Django are made up of Operations, and the main operation you use for data migrations is RunPython. To start, make an empty migration file you can work from (Django will put the file in the right place, suggest a name, and add dependencies for you): python manage.py makemigrations --empty yourappname
Then, open up the file; it should look something like this: # Generated by Django A.B on YYYY-MM-DD HH:MM
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
]
Now, all you need to do is create a new function and have RunPython use it. RunPython expects a callable as its argument which takes two arguments - the first is an app registry that has the historical versions of all your models loaded into it to match where in your history the migration sits, and the second is a SchemaEditor, which you can use to manually effect database schema changes (but beware, doing this can confuse the migration autodetector!) Let’s write a migration that populates our new name field with the combined values of first_name and last_name (we’ve come to our senses and realized that not everyone has first and last names). All we need to do is use the historical model and iterate over the rows: from django.db import migrations
def combine_names(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model('yourappname', 'Person')
for person in Person.objects.all():
person.name = '%s %s' % (person.first_name, person.last_name)
person.save()
class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(combine_names),
]
Once that’s done, we can run python manage.py migrate as normal and the data migration will run in place alongside other migrations. You can pass a second callable to RunPython to run whatever logic you want executed when migrating backwards. If this callable is omitted, migrating backwards will raise an exception. Accessing models from other apps When writing a RunPython function that uses models from apps other than the one in which the migration is located, the migration’s dependencies attribute should include the latest migration of each app that is involved, otherwise you may get an error similar to: LookupError: No installed app
with label 'myappname' when you try to retrieve the model in the RunPython function using apps.get_model(). In the following example, we have a migration in app1 which needs to use models in app2. We aren’t concerned with the details of move_m1 other than the fact it will need to access models from both apps. Therefore we’ve added a dependency that specifies the last migration of app2: class Migration(migrations.Migration):
dependencies = [
('app1', '0001_initial'),
# added dependency to enable using models from app2 in move_m1
('app2', '0004_foobar'),
]
operations = [
migrations.RunPython(move_m1),
]
More advanced migrations If you’re interested in the more advanced migration operations, or want to be able to write your own, see the migration operations reference and the “how-to” on writing migrations. Squashing migrations You are encouraged to make migrations freely and not worry about how many you have; the migration code is optimized to deal with hundreds at a time without much slowdown. However, eventually you will want to move back from having several hundred migrations to just a few, and that’s where squashing comes in. Squashing is the act of reducing an existing set of many migrations down to one (or sometimes a few) migrations which still represent the same changes. Django does this by taking all of your existing migrations, extracting their Operations and putting them all in sequence, and then running an optimizer over them to try and reduce the length of the list - for example, it knows that CreateModel and DeleteModel cancel each other out, and it knows that AddField can be rolled into CreateModel. Once the operation sequence has been reduced as much as possible - the amount possible depends on how closely intertwined your models are and if you have any RunSQL or RunPython operations (which can’t be optimized through unless they are marked as elidable) - Django will then write it back out into a new set of migration files. These files are marked to say they replace the previously-squashed migrations, so they can coexist with the old migration files, and Django will intelligently switch between them depending where you are in the history. If you’re still part-way through the set of migrations that you squashed, it will keep using them until it hits the end and then switch to the squashed history, while new installs will use the new squashed migration and skip all the old ones. This enables you to squash and not mess up systems currently in production that aren’t fully up-to-date yet. The recommended process is to squash, keeping the old files, commit and release, wait until all systems are upgraded with the new release (or if you’re a third-party project, ensure your users upgrade releases in order without skipping any), and then remove the old files, commit and do a second release. The command that backs all this is squashmigrations - pass it the app label and migration name you want to squash up to, and it’ll get to work: $ ./manage.py squashmigrations myapp 0004
Will squash the following migrations:
- 0001_initial
- 0002_some_change
- 0003_another_change
- 0004_undo_something
Do you wish to proceed? [yN] y
Optimizing...
Optimized from 12 operations to 7 operations.
Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py
You should commit this migration but leave the old ones in place;
the new migration will be used for new installs. Once you are sure
all instances of the codebase have applied the migrations you squashed,
you can delete them.
Use the squashmigrations --squashed-name option if you want to set the name of the squashed migration rather than use an autogenerated one. Note that model interdependencies in Django can get very complex, and squashing may result in migrations that do not run; either mis-optimized (in which case you can try again with --no-optimize, though you should also report an issue), or with a CircularDependencyError, in which case you can manually resolve it. To manually resolve a CircularDependencyError, break out one of the ForeignKeys in the circular dependency loop into a separate migration, and move the dependency on the other app with it. If you’re unsure, see how makemigrations deals with the problem when asked to create brand new migrations from your models. In a future release of Django, squashmigrations will be updated to attempt to resolve these errors itself. Once you’ve squashed your migration, you should then commit it alongside the migrations it replaces and distribute this change to all running instances of your application, making sure that they run migrate to store the change in their database. You must then transition the squashed migration to a normal migration by: Deleting all the migration files it replaces. Updating all migrations that depend on the deleted migrations to depend on the squashed migration instead. Removing the replaces attribute in the Migration class of the squashed migration (this is how Django tells that it is a squashed migration). Note Once you’ve squashed a migration, you should not then re-squash that squashed migration until you have fully transitioned it to a normal migration. Serializing values Migrations are Python files containing the old definitions of your models - thus, to write them, Django must take the current state of your models and serialize them out into a file. While Django can serialize most things, there are some things that we just can’t serialize out into a valid Python representation - there’s no Python standard for how a value can be turned back into code (repr() only works for basic values, and doesn’t specify import paths). Django can serialize the following:
int, float, bool, str, bytes, None, NoneType
list, set, tuple, dict, range.
datetime.date, datetime.time, and datetime.datetime instances (include those that are timezone-aware)
decimal.Decimal instances
enum.Enum instances
uuid.UUID instances
functools.partial() and functools.partialmethod instances which have serializable func, args, and keywords values. Pure and concrete path objects from pathlib. Concrete paths are converted to their pure path equivalent, e.g. pathlib.PosixPath to pathlib.PurePosixPath.
os.PathLike instances, e.g. os.DirEntry, which are converted to str or bytes using os.fspath().
LazyObject instances which wrap a serializable value. Enumeration types (e.g. TextChoices or IntegerChoices) instances. Any Django field Any function or method reference (e.g. datetime.datetime.today) (must be in module’s top-level scope) Unbound methods used from within the class body Any class reference (must be in module’s top-level scope) Anything with a custom deconstruct() method (see below) Changed in Django 3.2: Serialization support for pure and concrete path objects from pathlib, and os.PathLike instances was added. Django cannot serialize: Nested classes Arbitrary class instances (e.g. MyClass(4.3, 5.7)) Lambdas Custom serializers You can serialize other types by writing a custom serializer. For example, if Django didn’t serialize Decimal by default, you could do this: from decimal import Decimal
from django.db.migrations.serializer import BaseSerializer
from django.db.migrations.writer import MigrationWriter
class DecimalSerializer(BaseSerializer):
def serialize(self):
return repr(self.value), {'from decimal import Decimal'}
MigrationWriter.register_serializer(Decimal, DecimalSerializer)
The first argument of MigrationWriter.register_serializer() is a type or iterable of types that should use the serializer. The serialize() method of your serializer must return a string of how the value should appear in migrations and a set of any imports that are needed in the migration. Adding a deconstruct() method You can let Django serialize your own custom class instances by giving the class a deconstruct() method. It takes no arguments, and should return a tuple of three things (path, args, kwargs):
path should be the Python path to the class, with the class name included as the last part (for example, myapp.custom_things.MyClass). If your class is not available at the top level of a module it is not serializable.
args should be a list of positional arguments to pass to your class’ __init__ method. Everything in this list should itself be serializable.
kwargs should be a dict of keyword arguments to pass to your class’ __init__ method. Every value should itself be serializable. Note This return value is different from the deconstruct() method for custom fields which returns a tuple of four items. Django will write out the value as an instantiation of your class with the given arguments, similar to the way it writes out references to Django fields. To prevent a new migration from being created each time makemigrations is run, you should also add a __eq__() method to the decorated class. This function will be called by Django’s migration framework to detect changes between states. As long as all of the arguments to your class’ constructor are themselves serializable, you can use the @deconstructible class decorator from django.utils.deconstruct to add the deconstruct() method: from django.utils.deconstruct import deconstructible
@deconstructible
class MyCustomClass:
def __init__(self, foo=1):
self.foo = foo
...
def __eq__(self, other):
return self.foo == other.foo
The decorator adds logic to capture and preserve the arguments on their way into your constructor, and then returns those arguments exactly when deconstruct() is called. Supporting multiple Django versions If you are the maintainer of a third-party app with models, you may need to ship migrations that support multiple Django versions. In this case, you should always run makemigrations with the lowest Django version you wish to support. The migrations system will maintain backwards-compatibility according to the same policy as the rest of Django, so migration files generated on Django X.Y should run unchanged on Django X.Y+1. The migrations system does not promise forwards-compatibility, however. New features may be added, and migration files generated with newer versions of Django may not work on older versions. See also The Migrations Operations Reference Covers the schema operations API, special operations, and writing your own operations. The Writing Migrations “how-to” Explains how to structure and write database migrations for different scenarios you might encounter. | django.topics.migrations |
Models Model API reference. For introductory material, see Models. Model field reference Field attribute reference Model index reference Constraints reference Model _meta API Related objects reference Model class reference Model Meta options Model instance reference QuerySet API reference Lookup API reference Query Expressions Conditional Expressions Database Functions | django.ref.models.index |
Models A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries. Quick example This example model defines a Person, which has a first_name and last_name: from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column. The above Person model would create a database table like this: CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
Some technical notes: The name of the table, myapp_person, is automatically derived from some model metadata but can be overridden. See Table names for more details. An id field is added automatically, but this behavior can be overridden. See Automatic primary key fields. The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it’s worth noting Django uses SQL tailored to the database backend specified in your settings file. Using models Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py. For example, if the models for your application live in the module myapp.models (the package structure that is created for an application by the manage.py startapp script), INSTALLED_APPS should read, in part: INSTALLED_APPS = [
#...
'myapp',
#...
]
When you add new apps to INSTALLED_APPS, be sure to run manage.py migrate, optionally making migrations for them first with manage.py makemigrations. Fields The most important part of a model – and the only required part of a model – is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. Example: from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
Field types Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things: The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT). The default HTML widget to use when rendering a form field (e.g. <input type="text">, <select>). The minimal validation requirements, used in Django’s admin and in automatically-generated forms. Django ships with dozens of built-in field types; you can find the complete list in the model field reference. You can easily write your own fields if Django’s built-in ones don’t do the trick; see How to create custom model fields. Field options Each field takes a certain set of field-specific arguments (documented in the model field reference). For example, CharField (and its subclasses) require a max_length argument which specifies the size of the VARCHAR database field used to store the data. There’s also a set of common arguments available to all field types. All are optional. They’re fully explained in the reference, but here’s a quick summary of the most often-used ones:
null
If True, Django will store empty values as NULL in the database. Default is False.
blank
If True, the field is allowed to be blank. Default is False. Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.
choices
A sequence of 2-tuples to use as choices for this field. If this is given, the default form widget will be a select box instead of the standard text field and will limit choices to the choices given. A choices list looks like this: YEAR_IN_SCHOOL_CHOICES = [
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
]
Note A new migration is created each time the order of choices changes. The first element in each tuple is the value that will be stored in the database. The second element is displayed by the field’s form widget. Given a model instance, the display value for a field with choices can be accessed using the get_FOO_display() method. For example: from django.db import models
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display()
'Large'
You can also use enumeration classes to define choices in a concise way: from django.db import models
class Runner(models.Model):
MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
name = models.CharField(max_length=60)
medal = models.CharField(blank=True, choices=MedalType.choices, max_length=10)
Further examples are available in the model field reference.
default
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_text
Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_key
If True, this field is the primary key for the model. If you don’t specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields. The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one. For example: from django.db import models
class Fruit(models.Model):
name = models.CharField(max_length=100, primary_key=True)
>>> fruit = Fruit.objects.create(name='Apple')
>>> fruit.name = 'Pear'
>>> fruit.save()
>>> Fruit.objects.values_list('name', flat=True)
<QuerySet ['Apple', 'Pear']>
unique
If True, this field must be unique throughout the table. Again, these are just short descriptions of the most common field options. Full details can be found in the common model field option reference. Automatic primary key fields By default, Django gives each model an auto-incrementing primary key with the type specified per app in AppConfig.default_auto_field or globally in the DEFAULT_AUTO_FIELD setting. For example: id = models.BigAutoField(primary_key=True)
If you’d like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added). Changed in Django 3.2: In older versions, auto-created primary key fields were always AutoFields. Verbose field names Each field type, except for ForeignKey, ManyToManyField and OneToOneField, takes an optional first positional argument – a verbose name. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. In this example, the verbose name is "person's first name": first_name = models.CharField("person's first name", max_length=30)
In this example, the verbose name is "first name": first_name = models.CharField(max_length=30)
ForeignKey, ManyToManyField and OneToOneField require the first argument to be a model class, so use the verbose_name keyword argument: poll = models.ForeignKey(
Poll,
on_delete=models.CASCADE,
verbose_name="the related poll",
)
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
verbose_name="related place",
)
The convention is not to capitalize the first letter of the verbose_name. Django will automatically capitalize the first letter where it needs to. Relationships Clearly, the power of relational databases lies in relating tables to each other. Django offers ways to define the three most common types of database relationships: many-to-one, many-to-many and one-to-one. Many-to-one relationships To define a many-to-one relationship, use django.db.models.ForeignKey. You use it just like any other Field type: by including it as a class attribute of your model. ForeignKey requires a positional argument: the class to which the model is related. For example, if a Car model has a Manufacturer – that is, a Manufacturer makes multiple cars but each Car only has one Manufacturer – use the following definitions: from django.db import models
class Manufacturer(models.Model):
# ...
pass
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
# ...
You can also create recursive relationships (an object with a many-to-one relationship to itself) and relationships to models not yet defined; see the model field reference for details. It’s suggested, but not required, that the name of a ForeignKey field (manufacturer in the example above) be the name of the model, lowercase. You can call the field whatever you want. For example: class Car(models.Model):
company_that_makes_it = models.ForeignKey(
Manufacturer,
on_delete=models.CASCADE,
)
# ...
See also ForeignKey fields accept a number of extra arguments which are explained in the model field reference. These options help define how the relationship should work; all are optional. For details on accessing backwards-related objects, see the Following relationships backward example. For sample code, see the Many-to-one relationship model example. Many-to-many relationships To define a many-to-many relationship, use ManyToManyField. You use it just like any other Field type: by including it as a class attribute of your model. ManyToManyField requires a positional argument: the class to which the model is related. For example, if a Pizza has multiple Topping objects – that is, a Topping can be on multiple pizzas and each Pizza has multiple toppings – here’s how you’d represent that: from django.db import models
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
As with ForeignKey, you can also create recursive relationships (an object with a many-to-many relationship to itself) and relationships to models not yet defined. It’s suggested, but not required, that the name of a ManyToManyField (toppings in the example above) be a plural describing the set of related model objects. It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models – not both. Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because it’s more natural to think about a pizza having toppings than a topping being on multiple pizzas. The way it’s set up above, the Pizza form would let users select the toppings. See also See the Many-to-many relationship model example for a full example. ManyToManyField fields also accept a number of extra arguments which are explained in the model field reference. These options help define how the relationship should work; all are optional. Extra fields on many-to-many relationships When you’re only dealing with many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models. For example, consider the case of an application tracking the musical groups which musicians belong to. There is a many-to-many relationship between a person and the groups of which they are a member, so you could use a ManyToManyField to represent this relationship. However, there is a lot of detail about the membership that you might want to collect, such as the date at which the person joined the group. For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this: from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the many-to-many relationship. This explicit declaration defines how the two models are related. There are a few restrictions on the intermediate model: Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.through_fields. If you have more than one foreign key and through_fields is not specified, a validation error will be raised. A similar restriction applies to the foreign key to the target model (this would be Person in our example). For a model which has a many-to-many relationship to itself through an intermediary model, two foreign keys to the same model are permitted, but they will be treated as the two (different) sides of the many-to-many relationship. If there are more than two foreign keys though, you must also specify through_fields as above, or a validation error will be raised. Now that you have set up your ManyToManyField to use your intermediary model (Membership, in this case), you’re ready to start creating some many-to-many relationships. You do this by creating instances of the intermediate model: >>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
... date_joined=date(1962, 8, 16),
... invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>
>>> ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>
>>> m2 = Membership.objects.create(person=paul, group=beatles,
... date_joined=date(1960, 8, 1),
... invite_reason="Wanted to form a band.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>
You can also use add(), create(), or set() to create relationships, as long as you specify through_defaults for any required fields: >>> beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)})
>>> beatles.members.create(name="George Harrison", through_defaults={'date_joined': date(1960, 8, 1)})
>>> beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})
You may prefer to create instances of the intermediate model directly. If the custom through table defined by the intermediate model does not enforce uniqueness on the (model1, model2) pair, allowing multiple values, the remove() call will remove all intermediate model instances: >>> Membership.objects.create(person=ringo, group=beatles,
... date_joined=date(1968, 9, 4),
... invite_reason="You've been gone for a month and we miss you.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
>>> # This deletes both of the intermediate model instances for Ringo Starr
>>> beatles.members.remove(ringo)
>>> beatles.members.all()
<QuerySet [<Person: Paul McCartney>]>
The clear() method can be used to remove all many-to-many relationships for an instance: >>> # Beatles have broken up
>>> beatles.members.clear()
>>> # Note that this deletes the intermediate model instances
>>> Membership.objects.all()
<QuerySet []>
Once you have established the many-to-many relationships, you can issue queries. Just as with normal many-to-many relationships, you can query using the attributes of the many-to-many-related model: # Find all the groups with a member whose name starts with 'Paul'
>>> Group.objects.filter(members__name__startswith='Paul')
<QuerySet [<Group: The Beatles>]>
As you are using an intermediate model, you can also query on its attributes: # Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
... group__name='The Beatles',
... membership__date_joined__gt=date(1961,1,1))
<QuerySet [<Person: Ringo Starr]>
If you need to access a membership’s information you may do so by directly querying the Membership model: >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
Another way to access the same information is by querying the many-to-many reverse relationship from a Person object: >>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
One-to-one relationships To define a one-to-one relationship, use OneToOneField. You use it just like any other Field type: by including it as a class attribute of your model. This is most useful on the primary key of an object when that object “extends” another object in some way. OneToOneField requires a positional argument: the class to which the model is related. For example, if you were building a database of “places”, you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place (because a restaurant “is a” place; in fact, to handle this you’d typically use inheritance, which involves an implicit one-to-one relation). As with ForeignKey, a recursive relationship can be defined and references to as-yet undefined models can be made. See also See the One-to-one relationship model example for a full example. OneToOneField fields also accept an optional parent_link argument. OneToOneField classes used to automatically become the primary key on a model. This is no longer true (although you can manually pass in the primary_key argument if you like). Thus, it’s now possible to have multiple fields of type OneToOneField on a single model. Models across files It’s perfectly OK to relate a model to one from another app. To do this, import the related model at the top of the file where your model is defined. Then, refer to the other model class wherever needed. For example: from django.db import models
from geography.models import ZipCode
class Restaurant(models.Model):
# ...
zip_code = models.ForeignKey(
ZipCode,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
Field name restrictions Django places some restrictions on model field names:
A field name cannot be a Python reserved word, because that would result in a Python syntax error. For example: class Example(models.Model):
pass = models.IntegerField() # 'pass' is a reserved word!
A field name cannot contain more than one underscore in a row, due to the way Django’s query lookup syntax works. For example: class Example(models.Model):
foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
A field name cannot end with an underscore, for similar reasons. These limitations can be worked around, though, because your field name doesn’t necessarily have to match your database column name. See the db_column option. SQL reserved words, such as join, where or select, are allowed as model field names, because Django escapes all database table names and column names in every underlying SQL query. It uses the quoting syntax of your particular database engine. Custom field types If one of the existing model fields cannot be used to fit your purposes, or if you wish to take advantage of some less common database column types, you can create your own field class. Full coverage of creating your own fields is provided in How to create custom model fields.
Meta options Give your model metadata by using an inner class Meta, like so: from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"
Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class
Meta to a model is completely optional. A complete list of all possible Meta options can be found in the model option reference. Model attributes
objects The most important attribute of a model is the Manager. It’s the interface through which database query operations are provided to Django models and is used to retrieve the instances from the database. If no custom Manager is defined, the default name is objects. Managers are only accessible via model classes, not the model instances. Model methods Define custom methods on a model to add custom “row-level” functionality to your objects. Whereas Manager methods are intended to do “table-wide” things, model methods should act on a particular model instance. This is a valuable technique for keeping business logic in one place – the model. For example, this model has a few custom methods: from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
@property
def full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
The last method in this example is a property. The model instance reference has a complete list of methods automatically given to each model. You can override most of these – see overriding predefined model methods, below – but there are a couple that you’ll almost always want to define:
__str__()
A Python “magic method” that returns a string representation of any object. This is what Python and Django will use whenever a model instance needs to be coerced and displayed as a plain string. Most notably, this happens when you display an object in an interactive console or in the admin. You’ll always want to define this method; the default isn’t very helpful at all.
get_absolute_url()
This tells Django how to calculate the URL for an object. Django uses this in its admin interface, and any time it needs to figure out a URL for an object. Any object that has a URL that uniquely identifies it should define this method. Overriding predefined model methods There’s another set of model methods that encapsulate a bunch of database behavior that you’ll want to customize. In particular you’ll often want to change the way save() and delete() work. You’re free to override these methods (and any other model method) to alter behavior. A classic use-case for overriding the built-in methods is if you want something to happen whenever you save an object. For example (see save() for documentation of the parameters it accepts): from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
do_something()
super().save(*args, **kwargs) # Call the "real" save() method.
do_something_else()
You can also prevent saving: from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
if self.name == "Yoko Ono's blog":
return # Yoko shall never have her own blog!
else:
super().save(*args, **kwargs) # Call the "real" save() method.
It’s important to remember to call the superclass method – that’s that super().save(*args, **kwargs) business – to ensure that the object still gets saved into the database. If you forget to call the superclass method, the default behavior won’t happen and the database won’t get touched. It’s also important that you pass through the arguments that can be passed to the model method – that’s what the *args, **kwargs bit does. Django will, from time to time, extend the capabilities of built-in model methods, adding new arguments. If you use *args,
**kwargs in your method definitions, you are guaranteed that your code will automatically support those arguments when they are added. Overridden model methods are not called on bulk operations Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading
delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals. Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called. Executing custom SQL Another common pattern is writing custom SQL statements in model methods and module-level methods. For more details on using raw SQL, see the documentation on using raw SQL. Model inheritance Model inheritance in Django works almost identically to the way normal class inheritance works in Python, but the basics at the beginning of the page should still be followed. That means the base class should subclass django.db.models.Model. The only decision you have to make is whether you want the parent models to be models in their own right (with their own database tables), or if the parents are just holders of common information that will only be visible through the child models. There are three styles of inheritance that are possible in Django. Often, you will just want to use the parent class to hold information that you don’t want to have to type out for each child model. This class isn’t going to ever be used in isolation, so Abstract base classes are what you’re after. If you’re subclassing an existing model (perhaps something from another application entirely) and want each model to have its own database table, Multi-table inheritance is the way to go. Finally, if you only want to modify the Python-level behavior of a model, without changing the models fields in any way, you can use Proxy models. Abstract base classes Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class. An example: from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
class Student(CommonInfo):
home_group = models.CharField(max_length=5)
The Student model will have three fields: name, age and home_group. The CommonInfo model cannot be used as a normal Django model, since it is an abstract base class. It does not generate a database table or have a manager, and cannot be instantiated or saved directly. Fields inherited from abstract base classes can be overridden with another field or value, or be removed with None. For many uses, this type of model inheritance will be exactly what you want. It provides a way to factor out common information at the Python level, while still only creating one database table per child model at the database level.
Meta inheritance When an abstract base class is created, Django makes any Meta inner class you declared in the base class available as an attribute. If a child class does not declare its own Meta class, it will inherit the parent’s Meta. If the child wants to extend the parent’s Meta class, it can subclass it. For example: from django.db import models
class CommonInfo(models.Model):
# ...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
# ...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don’t automatically become abstract classes themselves. To make an abstract base class that inherits from another abstract base class, you need to explicitly set abstract=True on the child. Some attributes won’t make sense to include in the Meta class of an abstract base class. For example, including db_table would mean that all the child classes (the ones that don’t specify their own Meta) would use the same database table, which is almost certainly not what you want. Due to the way Python inheritance works, if a child class inherits from multiple abstract base classes, only the Meta options from the first listed class will be inherited by default. To inherit Meta options from multiple abstract base classes, you must explicitly declare the Meta inheritance. For example: from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
ordering = ['name']
class Unmanaged(models.Model):
class Meta:
abstract = True
managed = False
class Student(CommonInfo, Unmanaged):
home_group = models.CharField(max_length=5)
class Meta(CommonInfo.Meta, Unmanaged.Meta):
pass
Be careful with related_name and related_query_name
If you are using related_name or related_query_name on a ForeignKey or ManyToManyField, you must always specify a unique reverse name and query name for the field. This would normally cause a problem in abstract base classes, since the fields on this class are included into each of the child classes, with exactly the same values for the attributes (including related_name and related_query_name) each time. To work around this problem, when you are using related_name or related_query_name in an abstract base class (only), part of the value should contain '%(app_label)s' and '%(class)s'.
'%(class)s' is replaced by the lowercased name of the child class that the field is used in.
'%(app_label)s' is replaced by the lowercased name of the app the child class is contained within. Each installed application name must be unique and the model class names within each app must also be unique, therefore the resulting name will end up being different. For example, given an app common/models.py: from django.db import models
class Base(models.Model):
m2m = models.ManyToManyField(
OtherModel,
related_name="%(app_label)s_%(class)s_related",
related_query_name="%(app_label)s_%(class)ss",
)
class Meta:
abstract = True
class ChildA(Base):
pass
class ChildB(Base):
pass
Along with another app rare/models.py: from common.models import Base
class ChildB(Base):
pass
The reverse name of the common.ChildA.m2m field will be common_childa_related and the reverse query name will be common_childas. The reverse name of the common.ChildB.m2m field will be common_childb_related and the reverse query name will be common_childbs. Finally, the reverse name of the rare.ChildB.m2m field will be rare_childb_related and the reverse query name will be rare_childbs. It’s up to you how you use the '%(class)s' and '%(app_label)s' portion to construct your related name or related query name but if you forget to use it, Django will raise errors when you perform system checks (or run migrate). If you don’t specify a related_name attribute for a field in an abstract base class, the default reverse name will be the name of the child class followed by '_set', just as it normally would be if you’d declared the field directly on the child class. For example, in the above code, if the related_name attribute was omitted, the reverse name for the m2m field would be childa_set in the ChildA case and childb_set for the ChildB field. Multi-table inheritance The second type of model inheritance supported by Django is when each model in the hierarchy is a model all by itself. Each model corresponds to its own database table and can be queried and created individually. The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField). For example: from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
All of the fields of Place will also be available in Restaurant, although the data will reside in a different database table. So these are both possible: >>> Place.objects.filter(name="Bob's Cafe")
>>> Restaurant.objects.filter(name="Bob's Cafe")
If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using the lowercase version of the model name: >>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
However, if p in the above example was not a Restaurant (it had been created directly as a Place object or was the parent of some other class), referring to p.restaurant would raise a Restaurant.DoesNotExist exception. The automatically-created OneToOneField on Restaurant that links it to Place looks like this: place_ptr = models.OneToOneField(
Place, on_delete=models.CASCADE,
parent_link=True,
primary_key=True,
)
You can override that field by declaring your own OneToOneField with parent_link=True on Restaurant.
Meta and multi-table inheritance In the multi-table inheritance situation, it doesn’t make sense for a child class to inherit from its parent’s Meta class. All the Meta options have already been applied to the parent class and applying them again would normally only lead to contradictory behavior (this is in contrast with the abstract base class case, where the base class doesn’t exist in its own right). So a child model does not have access to its parent’s Meta class. However, there are a few limited cases where the child inherits behavior from the parent: if the child does not specify an ordering attribute or a get_latest_by attribute, it will inherit these from its parent. If the parent has an ordering and you don’t want the child to have any natural ordering, you can explicitly disable it: class ChildModel(ParentModel):
# ...
class Meta:
# Remove parent's ordering effect
ordering = []
Inheritance and reverse relations Because multi-table inheritance uses an implicit OneToOneField to link the child and the parent, it’s possible to move from the parent down to the child, as in the above example. However, this uses up the name that is the default related_name value for ForeignKey and ManyToManyField relations. If you are putting those types of relations on a subclass of the parent model, you must specify the related_name attribute on each such field. If you forget, Django will raise a validation error. For example, using the above Place class again, let’s create another subclass with a ManyToManyField: class Supplier(Place):
customers = models.ManyToManyField(Place)
This results in the error: Reverse query name for 'Supplier.customers' clashes with reverse query
name for 'Supplier.place_ptr'.
HINT: Add or change a related_name argument to the definition for
'Supplier.customers' or 'Supplier.place_ptr'.
Adding related_name to the customers field as follows would resolve the error: models.ManyToManyField(Place, related_name='provider'). Specifying the parent link field As mentioned, Django will automatically create a OneToOneField linking your child class back to any non-abstract parent models. If you want to control the name of the attribute linking back to the parent, you can create your own OneToOneField and set parent_link=True to indicate that your field is the link back to the parent class. Proxy models When using multi-table inheritance, a new database table is created for each subclass of a model. This is usually the desired behavior, since the subclass needs a place to store any additional data fields that are not present on the base class. Sometimes, however, you only want to change the Python behavior of a model – perhaps to change the default manager, or add a new method. This is what proxy model inheritance is for: creating a proxy for the original model. You can create, delete and update instances of the proxy model and all the data will be saved as if you were using the original (non-proxied) model. The difference is that you can change things like the default model ordering or the default manager in the proxy, without having to alter the original. Proxy models are declared like normal models. You tell Django that it’s a proxy model by setting the proxy attribute of the Meta class to True. For example, suppose you want to add a method to the Person model. You can do it like this: from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class MyPerson(Person):
class Meta:
proxy = True
def do_something(self):
# ...
pass
The MyPerson class operates on the same database table as its parent Person class. In particular, any new instances of Person will also be accessible through MyPerson, and vice-versa: >>> p = Person.objects.create(first_name="foobar")
>>> MyPerson.objects.get(first_name="foobar")
<MyPerson: foobar>
You could also use a proxy model to define a different default ordering on a model. You might not always want to order the Person model, but regularly order by the last_name attribute when you use the proxy: class OrderedPerson(Person):
class Meta:
ordering = ["last_name"]
proxy = True
Now normal Person queries will be unordered and OrderedPerson queries will be ordered by last_name. Proxy models inherit Meta attributes in the same way as regular models.
QuerySets still return the model that was requested There is no way to have Django return, say, a MyPerson object whenever you query for Person objects. A queryset for Person objects will return those types of objects. The whole point of proxy objects is that code relying on the original Person will use those and your own code can use the extensions you included (that no other code is relying on anyway). It is not a way to replace the Person (or any other) model everywhere with something of your own creation. Base class restrictions A proxy model must inherit from exactly one non-abstract model class. You can’t inherit from multiple non-abstract models as the proxy model doesn’t provide any connection between the rows in the different database tables. A proxy model can inherit from any number of abstract model classes, providing they do not define any model fields. A proxy model may also inherit from any number of proxy models that share a common non-abstract parent class. Proxy model managers If you don’t specify any model managers on a proxy model, it inherits the managers from its model parents. If you define a manager on the proxy model, it will become the default, although any managers defined on the parent classes will still be available. Continuing our example from above, you could change the default manager used when you query the Person model like this: from django.db import models
class NewManager(models.Manager):
# ...
pass
class MyPerson(Person):
objects = NewManager()
class Meta:
proxy = True
If you wanted to add a new manager to the Proxy, without replacing the existing default, you can use the techniques described in the custom manager documentation: create a base class containing the new managers and inherit that after the primary base class: # Create an abstract class for the new manager.
class ExtraManagers(models.Model):
secondary = NewManager()
class Meta:
abstract = True
class MyPerson(Person, ExtraManagers):
class Meta:
proxy = True
You probably won’t need to do this very often, but, when you do, it’s possible. Differences between proxy inheritance and unmanaged models Proxy model inheritance might look fairly similar to creating an unmanaged model, using the managed attribute on a model’s Meta class. With careful setting of Meta.db_table you could create an unmanaged model that shadows an existing model and adds Python methods to it. However, that would be very repetitive and fragile as you need to keep both copies synchronized if you make any changes. On the other hand, proxy models are intended to behave exactly like the model they are proxying for. They are always in sync with the parent model since they directly inherit its fields and managers. The general rules are: If you are mirroring an existing model or database table and don’t want all the original database table columns, use Meta.managed=False. That option is normally useful for modeling database views and tables not under the control of Django. If you are wanting to change the Python-only behavior of a model, but keep all the same fields as in the original, use Meta.proxy=True. This sets things up so that the proxy model is an exact copy of the storage structure of the original model when data is saved. Multiple inheritance Just as with Python’s subclassing, it’s possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, this means that if multiple parents contain a Meta class, only the first one is going to be used, and all others will be ignored. Generally, you won’t need to inherit from multiple parents. The main use-case where this is useful is for “mix-in” classes: adding a particular extra field or method to every class that inherits the mix-in. Try to keep your inheritance hierarchies as simple and straightforward as possible so that you won’t have to struggle to work out where a particular piece of information is coming from. Note that inheriting from multiple models that have a common id primary key field will raise an error. To properly use multiple inheritance, you can use an explicit AutoField in the base models: class Article(models.Model):
article_id = models.AutoField(primary_key=True)
...
class Book(models.Model):
book_id = models.AutoField(primary_key=True)
...
class BookReview(Book, Article):
pass
Or use a common ancestor to hold the AutoField. This requires using an explicit OneToOneField from each parent model to the common ancestor to avoid a clash between the fields that are automatically generated and inherited by the child: class Piece(models.Model):
pass
class Article(Piece):
article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
...
class Book(Piece):
book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
...
class BookReview(Book, Article):
pass
Field name “hiding” is not permitted In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class. This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None. Warning Model managers are inherited from abstract base classes. Overriding an inherited field which is referenced by an inherited Manager may cause subtle bugs. See custom managers and model inheritance. Note Some fields define extra attributes on the model, e.g. a ForeignKey defines an extra attribute with _id appended to the field name, as well as related_name and related_query_name on the foreign model. These extra attributes cannot be overridden unless the field that defines it is changed or removed so that it no longer defines the extra attribute. Overriding fields in a parent model leads to difficulties in areas such as initializing new instances (specifying which field is being initialized in Model.__init__) and serialization. These are features which normal Python class inheritance doesn’t have to deal with in quite the same way, so the difference between Django model inheritance and Python class inheritance isn’t arbitrary. This restriction only applies to attributes which are Field instances. Normal Python attributes can be overridden if you wish. It also only applies to the name of the attribute as Python sees it: if you are manually specifying the database column name, you can have the same column name appearing in both a child and an ancestor model for multi-table inheritance (they are columns in two different database tables). Django will raise a FieldError if you override any model field in any ancestor model. Note that because of the way fields are resolved during class definition, model fields inherited from multiple abstract parent models are resolved in a strict depth-first order. This contrasts with standard Python MRO, which is resolved breadth-first in cases of diamond shaped inheritance. This difference only affects complex model hierarchies, which (as per the advice above) you should try to avoid. Organizing models in a package The manage.py startapp command creates an application structure that includes a models.py file. If you have many models, organizing them in separate files may be useful. To do so, create a models package. Remove models.py and create a myapp/models/ directory with an __init__.py file and the files to store your models. You must import the models in the __init__.py file. For example, if you had organic.py and synthetic.py in the models directory: myapp/models/__init__.py from .organic import Person
from .synthetic import Robot
Explicitly importing each model rather than using from .models import * has the advantages of not cluttering the namespace, making code more readable, and keeping code analysis tools useful. See also The Models Reference Covers all the model related APIs including model fields, related objects, and QuerySet. | django.topics.db.models |
Pagination Django provides high-level and low-level ways to help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. The Paginator class Under the hood, all methods of pagination use the Paginator class. It does all the heavy lifting of actually splitting a QuerySet into Page objects. Example Give Paginator a list of objects, plus the number of items you’d like to have on each page, and it gives you methods for accessing the items for each page: >>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)
>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']
>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4
>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results
Note Note that you can give Paginator a list/tuple, a Django QuerySet, or any other object with a count() or __len__() method. When determining the number of objects contained in the passed object, Paginator will first try calling count(), then fallback to using len() if the passed object has no count() method. This allows objects such as Django’s QuerySet to use a more efficient count() method when available. Paginating a ListView
django.views.generic.list.ListView provides a builtin way to paginate the displayed list. You can do this by adding a paginate_by attribute to your view class, for example: from django.views.generic import ListView
from myapp.models import Contact
class ContactListView(ListView):
paginate_by = 2
model = Contact
This limits the number of objects per page and adds a paginator and page_obj to the context. To allow your users to navigate between pages, add links to the next and previous page, in your template like this: {% for contact in page_obj %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br>
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
Using Paginator in a view function Here’s an example using Paginator in a view function to paginate a queryset: from django.core.paginator import Paginator
from django.shortcuts import render
from myapp.models import Contact
def listing(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'list.html', {'page_obj': page_obj})
In the template list.html, you can include navigation between pages in the same way as in the template for the ListView above. | django.topics.pagination |
Paginator Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. These classes live in django/core/paginator.py. For examples, see the Pagination topic guide.
Paginator class
class Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
A paginator acts like a sequence of Page when using len() or iterating it directly.
Paginator.object_list
Required. A list, tuple, QuerySet, or other sliceable object with a count() or __len__() method. For consistent pagination, QuerySets should be ordered, e.g. with an order_by() clause or with a default ordering on the model. Performance issues paginating large QuerySets If you’re using a QuerySet with a very large number of items, requesting high page numbers might be slow on some databases, because the resulting LIMIT/OFFSET query needs to count the number of OFFSET records which takes longer as the page number gets higher.
Paginator.per_page
Required. The maximum number of items to include on a page, not including orphans (see the orphans optional argument below).
Paginator.orphans
Optional. Use this when you don’t want to have a last page with very few items. If the last page would normally have a number of items less than or equal to orphans, then those items will be added to the previous page (which becomes the last page) instead of leaving the items on a page by themselves. For example, with 23 items, per_page=10, and orphans=3, there will be two pages; the first page with 10 items and the second (and last) page with 13 items. orphans defaults to zero, which means pages are never combined and the last page may have one item.
Paginator.allow_empty_first_page
Optional. Whether or not the first page is allowed to be empty. If False and object_list is empty, then an EmptyPage error will be raised.
Methods
Paginator.get_page(number)
Returns a Page object with the given 1-based index, while also handling out of range and invalid page numbers. If the page isn’t a number, it returns the first page. If the page number is negative or greater than the number of pages, it returns the last page. Raises an EmptyPage exception only if you specify Paginator(..., allow_empty_first_page=False) and the object_list is empty.
Paginator.page(number)
Returns a Page object with the given 1-based index. Raises PageNotAnInteger if the number cannot be converted to an integer by calling int(). Raises EmptyPage if the given page number doesn’t exist.
Paginator.get_elided_page_range(number, *, on_each_side=3, on_ends=2)
New in Django 3.2. Returns a 1-based list of page numbers similar to Paginator.page_range, but may add an ellipsis to either or both sides of the current page number when Paginator.num_pages is large. The number of pages to include on each side of the current page number is determined by the on_each_side argument which defaults to 3. The number of pages to include at the beginning and end of page range is determined by the on_ends argument which defaults to 2. For example, with the default values for on_each_side and on_ends, if the current page is 10 and there are 50 pages, the page range will be [1, 2, '…', 7, 8, 9, 10, 11, 12, 13, '…', 49, 50]. This will result in pages 7, 8, and 9 to the left of and 11, 12, and 13 to the right of the current page as well as pages 1 and 2 at the start and 49 and 50 at the end. Raises InvalidPage if the given page number doesn’t exist.
Attributes
Paginator.ELLIPSIS
New in Django 3.2. A translatable string used as a substitute for elided page numbers in the page range returned by get_elided_page_range(). Default is '…'.
Paginator.count
The total number of objects, across all pages. Note When determining the number of objects contained in object_list, Paginator will first try calling object_list.count(). If object_list has no count() method, then Paginator will fall back to using len(object_list). This allows objects, such as QuerySet, to use a more efficient count() method when available.
Paginator.num_pages
The total number of pages.
Paginator.page_range
A 1-based range iterator of page numbers, e.g. yielding [1, 2, 3, 4].
Page class You usually won’t construct Page objects by hand – you’ll get them by iterating Paginator, or by using Paginator.page().
class Page(object_list, number, paginator)
A page acts like a sequence of Page.object_list when using len() or iterating it directly.
Methods
Page.has_next()
Returns True if there’s a next page.
Page.has_previous()
Returns True if there’s a previous page.
Page.has_other_pages()
Returns True if there’s a next or previous page.
Page.next_page_number()
Returns the next page number. Raises InvalidPage if next page doesn’t exist.
Page.previous_page_number()
Returns the previous page number. Raises InvalidPage if previous page doesn’t exist.
Page.start_index()
Returns the 1-based index of the first object on the page, relative to all of the objects in the paginator’s list. For example, when paginating a list of 5 objects with 2 objects per page, the second page’s start_index() would return 3.
Page.end_index()
Returns the 1-based index of the last object on the page, relative to all of the objects in the paginator’s list. For example, when paginating a list of 5 objects with 2 objects per page, the second page’s end_index() would return 4.
Attributes
Page.object_list
The list of objects on this page.
Page.number
The 1-based page number for this page.
Page.paginator
The associated Paginator object.
Exceptions
exception InvalidPage
A base class for exceptions raised when a paginator is passed an invalid page number.
The Paginator.page() method raises an exception if the requested page is invalid (i.e. not an integer) or contains no objects. Generally, it’s enough to catch the InvalidPage exception, but if you’d like more granularity, you can catch either of the following exceptions:
exception PageNotAnInteger
Raised when page() is given a value that isn’t an integer.
exception EmptyPage
Raised when page() is given a valid value but no objects exist on that page.
Both of the exceptions are subclasses of InvalidPage, so you can handle them both with except InvalidPage. | django.ref.paginator |
class ArrayAgg(expression, distinct=False, filter=None, default=None, ordering=(), **extra)
Returns a list of values, including nulls, concatenated into an array, or default if there are no values.
distinct
An optional boolean argument that determines if array 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 list. Examples: 'some_field'
'-some_field'
from django.db.models import F
F('some_field').desc()
Deprecated since version 4.0: If there are no rows and default is not provided, ArrayAgg returns an empty list 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.ArrayAgg |
distinct
An optional boolean argument that determines if array values will be distinct. Defaults to False. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.ArrayAgg.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 list. Examples: 'some_field'
'-some_field'
from django.db.models import F
F('some_field').desc() | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.ArrayAgg.ordering |
class BitAnd(expression, filter=None, default=None, **extra)
Returns an int of the bitwise AND of all non-null input values, or default if all values are null. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.BitAnd |
class BitOr(expression, filter=None, default=None, **extra)
Returns an int of the bitwise OR of all non-null input values, or default if all values are null. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.BitOr |
class BoolAnd(expression, filter=None, default=None, **extra)
Returns True, if all input values are true, default if all values are null or if there are no values, otherwise False. Usage example: class Comment(models.Model):
body = models.TextField()
published = models.BooleanField()
rank = models.IntegerField()
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolAnd
>>> Comment.objects.aggregate(booland=BoolAnd('published'))
{'booland': False}
>>> Comment.objects.aggregate(booland=BoolAnd(Q(rank__lt=100)))
{'booland': True} | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.BoolAnd |
class BoolOr(expression, filter=None, default=None, **extra)
Returns True if at least one input value is true, default if all values are null or if there are no values, otherwise False. Usage example: class Comment(models.Model):
body = models.TextField()
published = models.BooleanField()
rank = models.IntegerField()
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolOr
>>> Comment.objects.aggregate(boolor=BoolOr('published'))
{'boolor': True}
>>> Comment.objects.aggregate(boolor=BoolOr(Q(rank__gt=2)))
{'boolor': False} | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.BoolOr |
class Corr(y, x, filter=None, default=None)
Returns the correlation coefficient as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.Corr |
class CovarPop(y, x, sample=False, filter=None, default=None)
Returns the population covariance as a float, or default if there aren’t any matching rows. Has one optional argument:
sample
By default CovarPop returns the general population covariance. However, if sample=True, the return value will be the sample population covariance. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.CovarPop |
sample
By default CovarPop returns the general population covariance. However, if sample=True, the return value will be the sample population covariance. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.CovarPop.sample |
class JSONBAgg(expressions, distinct=False, filter=None, default=None, ordering=(), **extra)
Returns the input values as a JSON array, or default if there are no values. You can query the result using key and index lookups.
distinct
New in Django 3.2. An optional boolean argument that determines if array values will be distinct. Defaults to False.
ordering
New in Django 3.2. 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 list. Examples are the same as for ArrayAgg.ordering.
Usage example: class Room(models.Model):
number = models.IntegerField(unique=True)
class HotelReservation(model.Model):
room = models.ForeignKey('Room', on_delete=models.CASCADE)
start = models.DateTimeField()
end = models.DateTimeField()
requirements = models.JSONField(blank=True, null=True)
>>> from django.contrib.postgres.aggregates import JSONBAgg
>>> Room.objects.annotate(
... requirements=JSONBAgg(
... 'hotelreservation__requirements',
... ordering='-hotelreservation__start',
... )
... ).filter(requirements__0__sea_view=True).values('number', 'requirements')
<QuerySet [{'number': 102, 'requirements': [
{'parking': False, 'sea_view': True, 'double_bed': False},
{'parking': True, 'double_bed': True}
]}]>
Deprecated since version 4.0: If there are no rows and default is not provided, JSONBAgg returns an empty list 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.JSONBAgg |
distinct
New in Django 3.2. An optional boolean argument that determines if array values will be distinct. Defaults to False. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.JSONBAgg.distinct |
ordering
New in Django 3.2. 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 list. Examples are the same as for ArrayAgg.ordering. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.JSONBAgg.ordering |
class RegrAvgX(y, x, filter=None, default=None)
Returns the average of the independent variable (sum(x)/N) as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrAvgX |
class RegrAvgY(y, x, filter=None, default=None)
Returns the average of the dependent variable (sum(y)/N) as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrAvgY |
class RegrCount(y, x, filter=None)
Returns an int of the number of input rows in which both expressions are not null. Note The default argument is not supported. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrCount |
class RegrIntercept(y, x, filter=None, default=None)
Returns the y-intercept of the least-squares-fit linear equation determined by the (x, y) pairs as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrIntercept |
class RegrR2(y, x, filter=None, default=None)
Returns the square of the correlation coefficient as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrR2 |
class RegrSlope(y, x, filter=None, default=None)
Returns the slope of the least-squares-fit linear equation determined by the (x, y) pairs as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrSlope |
class RegrSXX(y, x, filter=None, default=None)
Returns sum(x^2) - sum(x)^2/N (“sum of squares” of the independent variable) as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrSXX |
class RegrSXY(y, x, filter=None, default=None)
Returns sum(x*y) - sum(x) * sum(y)/N (“sum of products” of independent times dependent variable) as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrSXY |
class RegrSYY(y, x, filter=None, default=None)
Returns sum(y^2) - sum(y)^2/N (“sum of squares” of the dependent variable) as a float, or default if there aren’t any matching rows. | django.ref.contrib.postgres.aggregates#django.contrib.postgres.aggregates.RegrSYY |
Subsets and Splits