Search A common task for web applications is to search some data in the database with user input. In a simple case, this could be filtering a list of objects by a category. A more complex use case might require searching with weighting, categorization, highlighting, multiple languages, and so on. This document explains some of the possible use cases and the tools you can use. We’ll refer to the same models used in Making queries. Use Cases Standard textual queries Text-based fields have a selection of matching operations. For example, you may wish to allow lookup up an author like so: >>> Author.objects.filter(name__contains='Terry')
[<Author: Terry Gilliam>, <Author: Terry Jones>]
 This is a very fragile solution as it requires the user to know an exact substring of the author’s name. A better approach could be a case-insensitive match (icontains), but this is only marginally better. A database’s more advanced comparison functions If you’re using PostgreSQL, Django provides a selection of database specific tools to allow you to leverage more complex querying options. Other databases have different selections of tools, possibly via plugins or user-defined functions. Django doesn’t include any support for them at this time. We’ll use some examples from PostgreSQL to demonstrate the kind of functionality databases may have.  Searching in other databases All of the searching tools provided by django.contrib.postgres are constructed entirely on public APIs such as custom lookups and database functions. Depending on your database, you should be able to construct queries to allow similar APIs. If there are specific things which cannot be achieved this way, please open a ticket.  In the above example, we determined that a case insensitive lookup would be more useful. When dealing with non-English names, a further improvement is to use unaccented comparison: >>> Author.objects.filter(name__unaccent__icontains='Helen')
[<Author: Helen Mirren>, <Author: Helena Bonham Carter>, <Author: Hélène Joy>]
 This shows another issue, where we are matching against a different spelling of the name. In this case we have an asymmetry though - a search for Helen will pick up Helena or Hélène, but not the reverse. Another option would be to use a trigram_similar comparison, which compares sequences of letters. For example: >>> Author.objects.filter(name__unaccent__lower__trigram_similar='Hélène')
[<Author: Helen Mirren>, <Author: Hélène Joy>]
 Now we have a different problem - the longer name of “Helena Bonham Carter” doesn’t show up as it is much longer. Trigram searches consider all combinations of three letters, and compares how many appear in both search and source strings. For the longer name, there are more combinations that don’t appear in the source string, so it is no longer considered a close match. The correct choice of comparison functions here depends on your particular data set, for example the language(s) used and the type of text being searched. All of the examples we’ve seen are on short strings where the user is likely to enter something close (by varying definitions) to the source data. Document-based search Standard database operations stop being a useful approach when you start considering large blocks of text. Whereas the examples above can be thought of as operations on a string of characters, full text search looks at the actual words. Depending on the system used, it’s likely to use some of the following ideas:  Ignoring “stop words” such as “a”, “the”, “and”. Stemming words, so that “pony” and “ponies” are considered similar. Weighting words based on different criteria such as how frequently they appear in the text, or the importance of the fields, such as the title or keywords, that they appear in.  There are many alternatives for using searching software, some of the most prominent are Elastic and Solr. These are full document-based search solutions. To use them with data from Django models, you’ll need a layer which translates your data into a textual document, including back-references to the database ids. When a search using the engine returns a certain document, you can then look it up in the database. There are a variety of third-party libraries which are designed to help with this process. PostgreSQL support PostgreSQL has its own full text search implementation built-in. While not as powerful as some other search engines, it has the advantage of being inside your database and so can easily be combined with other relational queries such as categorization. The django.contrib.postgres module provides some helpers to make these queries. For example, a query might select all the blog entries which mention “cheese”: >>> Entry.objects.filter(body_text__search='cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]
 You can also filter on a combination of fields and on related models: >>> Entry.objects.annotate(
...     search=SearchVector('blog__tagline', 'body_text'),
... ).filter(search='cheese')
[
    <Entry: Cheese on Toast recipes>,
    <Entry: Pizza Recipes>,
    <Entry: Dairy farming in Argentina>,
]
 See the contrib.postgres Full text search document for complete details.


class backends.base.SessionBase
This is the base class for all session objects. It has the following standard dictionary methods:
__getitem__(key)
Example: fav_color = request.session['fav_color']

__setitem__(key, value)
Example: request.session['fav_color'] = 'blue'

__delitem__(key)
Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.

__contains__(key)
Example: 'fav_color' in request.session

get(key, default=None)
Example: fav_color = request.session.get('fav_color', 'red')

pop(key, default=__not_given)
Example: fav_color = request.session.pop('fav_color', 'blue')

keys()

items()

setdefault()

clear()
 It also has these methods:
flush()
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).

set_test_cookie()
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information.

test_cookie_worked()
Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.

delete_test_cookie()
Deletes the test cookie. Use this to clean up after yourself.

get_session_cookie_age()
Returns the age of session cookies, in seconds. Defaults to SESSION_COOKIE_AGE.

set_expiry(value)
Sets the expiration time for the session. You can pass a number of different values:  If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer. If value is 0, the user’s session cookie will expire when the user’s web browser is closed. If value is None, the session reverts to using the global session expiry policy.  Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.

get_expiry_age()
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE. This function accepts two optional keyword arguments:
modification: last modification of the session, as a datetime object. Defaults to the current time.
expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.

get_expiry_date()
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date SESSION_COOKIE_AGE seconds from now. This function accepts the same keyword arguments as get_expiry_age().

get_expire_at_browser_close()
Returns either True or False, depending on whether the user’s session cookie will expire when the user’s web browser is closed.

clear_expired()
Removes expired sessions from the session store. This class method is called by clearsessions.

cycle_key()
Creates a new session key while retaining the current session data. django.contrib.auth.login() calls this method to mitigate against session fixation.


__contains__(key)
Example: 'fav_color' in request.session


__delitem__(key)
Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.


__getitem__(key)
Example: fav_color = request.session['fav_color']


__setitem__(key, value)
Example: request.session['fav_color'] = 'blue'


clear_expired()
Removes expired sessions from the session store. This class method is called by clearsessions.


cycle_key()
Creates a new session key while retaining the current session data. django.contrib.auth.login() calls this method to mitigate against session fixation.


delete_test_cookie()
Deletes the test cookie. Use this to clean up after yourself.


flush()
Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).


get(key, default=None)
Example: fav_color = request.session.get('fav_color', 'red')


get_expire_at_browser_close()
Returns either True or False, depending on whether the user’s session cookie will expire when the user’s web browser is closed.


get_expiry_age()
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE. This function accepts two optional keyword arguments:
modification: last modification of the session, as a datetime object. Defaults to the current time.
expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.


get_expiry_date()
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date SESSION_COOKIE_AGE seconds from now. This function accepts the same keyword arguments as get_expiry_age().


get_session_cookie_age()
Returns the age of session cookies, in seconds. Defaults to SESSION_COOKIE_AGE.


pop(key, default=__not_given)
Example: fav_color = request.session.pop('fav_color', 'blue')


set_expiry(value)
Sets the expiration time for the session. You can pass a number of different values:  If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes. If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer. If value is 0, the user’s session cookie will expire when the user’s web browser is closed. If value is None, the session reverts to using the global session expiry policy.  Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.


set_test_cookie()
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information.


test_cookie_worked()
Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.


class backends.cached_db.SessionStore
Implements cached database-backed session store.
cache_key_prefix
A prefix added to a session key to build a cache key string.


cache_key_prefix
A prefix added to a session key to build a cache key string.


class backends.db.SessionStore
Implements database-backed session store.
classmethod get_model_class()
Override this method to return a custom session model if you need one.

create_model_instance(data)
Returns a new instance of the session model object, which represents the current session state. Overriding this method provides the ability to modify session model data before it’s saved to database.


create_model_instance(data)
Returns a new instance of the session model object, which represents the current session state. Overriding this method provides the ability to modify session model data before it’s saved to database.


class base_session.AbstractBaseSession
The abstract base session model.
session_key
Primary key. The field itself may contain up to 40 characters. The current implementation generates a 32-character string (a random sequence of digits and lowercase ASCII letters).

session_data
A string containing an encoded and serialized session dictionary.

expire_date
A datetime designating when the session expires. Expired sessions are not available to a user, however, they may still be stored in the database until the clearsessions management command is run.

classmethod get_session_store_class()
Returns a session store class to be used with this session model.

get_decoded()
Returns decoded session data. Decoding is performed by the session store class.


expire_date
A datetime designating when the session expires. Expired sessions are not available to a user, however, they may still be stored in the database until the clearsessions management command is run.


get_decoded()
Returns decoded session data. Decoding is performed by the session store class.


session_data
A string containing an encoded and serialized session dictionary.


session_key
Primary key. The field itself may contain up to 40 characters. The current implementation generates a 32-character string (a random sequence of digits and lowercase ASCII letters).


class base_session.BaseSessionManager

encode(session_dict)
Returns the given session dictionary serialized and encoded as a string. Encoding is performed by the session store class tied to a model class.

save(session_key, session_dict, expire_date)
Saves session data for a provided session key, or deletes the session in case the data is empty.


encode(session_dict)
Returns the given session dictionary serialized and encoded as a string. Encoding is performed by the session store class tied to a model class.


save(session_key, session_dict, expire_date)
Saves session data for a provided session key, or deletes the session in case the data is empty.


class serializers.JSONSerializer
A wrapper around the JSON serializer from django.core.signing. Can only serialize basic data types. In addition, as JSON supports only string keys, note that using non-string keys in request.session won’t work as expected: >>> # initial assignment
>>> request.session[0] = 'bar'
>>> # subsequent requests following serialization & deserialization
>>> # of session data
>>> request.session[0]  # KeyError
>>> request.session['0']
'bar'
 Similarly, data that can’t be encoded in JSON, such as non-UTF8 bytes like '\xd9' (which raises UnicodeDecodeError), can’t be stored. See the Write your own serializer section for more details on limitations of JSON serialization.


class serializers.PickleSerializer
Supports arbitrary Python objects, but, as described above, can lead to a remote code execution vulnerability if SECRET_KEY becomes known by an attacker.