Django

Code

Show
Ignore:
Timestamp:
06/17/07 17:18:54 (2 years ago)
Author:
clong
Message:

per-object-permissions: Merged to trunk [5486] NOTE: Not fully tested, will be working on this over the next few weeks.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/per-object-permissions/docs/db-api.txt

    r4242 r5488  
    77objects. This document explains that API. 
    88 
    9 .. _`data models`: http://www.djangoproject.com/documentation/model_api/ 
     9.. _`data models`: ../model-api/ 
    1010 
    1111Throughout this reference, we'll refer to the following models, which comprise 
     
    8686`AutoField documentation`_.) 
    8787 
    88 .. _AutoField documentation: http://www.djangoproject.com/documentation/model_api/#autofield 
     88.. _AutoField documentation: ../model-api/#autofield 
    8989 
    9090Explicitly specifying auto-primary-key values 
     
    113113    b4.save()  # Overrides the previous blog with ID=3! 
    114114 
    115 See _`How Django knows to UPDATE vs. INSERT`, below, for the reason this 
     115See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this 
    116116happens. 
    117117 
     
    134134 
    135135The ``save()`` method has no return value. 
     136 
     137Updating ``ForeignKey`` fields works exactly the same way; simply assign an 
     138object of the right type to the field in question:: 
     139 
     140    joe = Author.objects.create(name="Joe") 
     141    entry.author = joe 
     142    entry.save() 
     143     
     144Django will complain if you try to assign an object of the wrong type. 
    136145 
    137146How Django knows to UPDATE vs. INSERT 
     
    144153 
    145154    * If the object's primary key attribute is set to a value that evaluates to 
    146       ``True`` (i.e., a value other than ``None`` or the empty string), Django  
    147       executes a ``SELECT`` query to determine whether a record with the given  
     155      ``True`` (i.e., a value other than ``None`` or the empty string), Django 
     156      executes a ``SELECT`` query to determine whether a record with the given 
    148157      primary key already exists. 
    149158    * If the record with the given primary key does already exist, Django 
     
    380389underlying SQL statement, and the whole thing is enclosed in a ``NOT()``. 
    381390 
    382 This example excludes all entries whose ``pub_date`` is the current date/time 
     391This example excludes all entries whose ``pub_date`` is later than 2005-1-3 
    383392AND whose ``headline`` is "Hello":: 
    384393 
     
    390399    WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello') 
    391400 
    392 This example excludes all entries whose ``pub_date`` is the current date/time 
    393 OR whose ``headline`` is "Hello":: 
     401This example excludes all entries whose ``pub_date`` is later than 2005-1-3 
     402AND whose headline is NOT "Hello":: 
    394403 
    395404    Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello') 
     
    527536    [datetime.datetime(2005, 3, 20)] 
    528537 
     538``none()`` 
     539~~~~~~~~~~ 
     540 
     541**New in Django development version** 
     542 
     543Returns an ``EmptyQuerySet`` -- a ``QuerySet`` that always evaluates to 
     544an empty list. This can be used in cases where you know that you should 
     545return an empty result set and your caller is expecting a ``QuerySet`` 
     546object (instead of returning an empty list, for example.) 
     547 
     548Examples:: 
     549 
     550    >>> Entry.objects.none() 
     551    [] 
     552 
    529553``select_related()`` 
    530554~~~~~~~~~~~~~~~~~~~~ 
     
    575599    c = p.hometown       # Doesn't hit the database. 
    576600 
    577     sv = Book.objects.get(id=4) # No select_related() in this example. 
     601    b = Book.objects.get(id=4) # No select_related() in this example. 
    578602    p = b.author         # Hits the database. 
    579603    c = p.hometown       # Hits the database. 
     
    581605Note that ``select_related()`` does not follow foreign keys that have 
    582606``null=True``. 
     607 
     608Usually, using ``select_related()`` can vastly improve performance because your 
     609app can avoid many database calls. However, in situations with deeply nested 
     610sets of relationships ``select_related()`` can sometimes end up following "too 
     611many" relations, and can generate queries so large that they end up being slow. 
     612 
     613In these situations, you can use the ``depth`` argument to ``select_related()`` 
     614to control how many "levels" of relations ``select_related()`` will actually 
     615follow:: 
     616 
     617    b = Book.objects.select_related(depth=1).get(id=4) 
     618    p = b.author         # Doesn't hit the database. 
     619    c = p.hometown       # Requires a database call. 
     620 
     621The ``depth`` argument is new in the Django development version. 
    583622 
    584623``extra(select=None, where=None, params=None, tables=None)`` 
     
    685724something *other than* a ``QuerySet``. 
    686725 
    687 These methods do not use a cache (see _`Caching and QuerySets` below). Rather, 
     726These methods do not use a cache (see `Caching and QuerySets`_ below). Rather, 
    688727they query the database each time they're called. 
    689728 
     
    877916~~~~~ 
    878917 
    879 Exact match. If the value provided for comparison is ``None``, it will  
    880 be interpreted as an SQL ``NULL`` (See isnull_ for more details).   
     918Exact match. If the value provided for comparison is ``None``, it will 
     919be interpreted as an SQL ``NULL`` (See isnull_ for more details). 
    881920 
    882921Examples:: 
     
    11071146~~~~~~ 
    11081147 
    1109 Takes either ``True`` or ``False``, which correspond to SQL queries of  
     1148Takes either ``True`` or ``False``, which correspond to SQL queries of 
    11101149``IS NULL`` and ``IS NOT NULL``, respectively. 
    11111150 
     
    11201159.. admonition:: ``__isnull=True`` vs ``__exact=None`` 
    11211160 
    1122     There is an important difference between ``__isnull=True`` and  
     1161    There is an important difference between ``__isnull=True`` and 
    11231162    ``__exact=None``. ``__exact=None`` will *always* return an empty result 
    1124     set, because SQL requires that no value is equal to ``NULL``.  
    1125     ``__isnull`` determines if the field is currently holding the value  
     1163    set, because SQL requires that no value is equal to ``NULL``. 
     1164    ``__isnull`` determines if the field is currently holding the value 
    11261165    of ``NULL`` without performing a comparison. 
    11271166 
     
    11521191 
    11531192For convenience, Django provides a ``pk`` lookup type, which stands for 
    1154 "primary_key".  
     1193"primary_key". 
    11551194 
    11561195In the example ``Blog`` model, the primary key is the ``id`` field, so these 
     
    11611200    Blog.objects.get(pk=14) # pk implies id__exact 
    11621201 
    1163 The use of ``pk`` isn't limited to ``__exact`` queries -- any query term  
     1202The use of ``pk`` isn't limited to ``__exact`` queries -- any query term 
    11641203can be combined with ``pk`` to perform a query on the primary key of a model:: 
    11651204 
     
    11671206    Blog.objects.filter(pk__in=[1,4,7]) 
    11681207    # Get all blog entries with id > 14 
    1169     Blog.objects.filter(pk__gt=14)  
    1170      
     1208    Blog.objects.filter(pk__gt=14) 
     1209 
    11711210``pk`` lookups also work across joins. For example, these three statements are 
    11721211equivalent:: 
     
    12001239    Blog.objects.filter(entry__headline__contains='Lennon') 
    12011240 
    1202 Escaping parenthesis and underscores in LIKE statements 
    1203 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     1241Escaping percent signs and underscores in LIKE statements 
     1242~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    12041243 
    12051244The field lookups that equate to ``LIKE`` SQL statements (``iexact``, 
     
    16071646    Entry.objects.filter(pub_date__year=2005).delete() 
    16081647 
     1648When Django deletes an object, it emulates the behavior of the SQL 
     1649constraint ``ON DELETE CASCADE`` -- in other words, any objects which 
     1650had foreign keys pointing at the object to be deleted will be deleted 
     1651along with it. For example:: 
     1652 
     1653    b = Blog.objects.get(pk=1) 
     1654    # This will delete the Blog and all of its Entry objects. 
     1655    b.delete() 
     1656 
    16091657Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a 
    16101658``Manager`` itself. This is a safety mechanism to prevent you from accidentally 
     
    17051753returns the height (or width) of the image, as an integer, in pixels. 
    17061754 
     1755Shortcuts 
     1756========= 
     1757 
     1758As you develop views, you will discover a number of common idioms in the 
     1759way you use the database API. Django encodes some of these idioms as 
     1760shortcuts that can be used to simplify the process of writing views. These 
     1761functions are in the ``django.shortcuts`` module. 
     1762 
     1763get_object_or_404() 
     1764------------------- 
     1765 
     1766One common idiom to use ``get()`` and raise ``Http404`` if the 
     1767object doesn't exist. This idiom is captured by ``get_object_or_404()``. 
     1768This function takes a Django model as its first argument and an 
     1769arbitrary number of keyword arguments, which it passes to the manager's 
     1770``get()`` function. It raises ``Http404`` if the object doesn't 
     1771exist. For example:: 
     1772 
     1773    # Get the Entry with a primary key of 3 
     1774    e = get_object_or_404(Entry, pk=3) 
     1775 
     1776When you provide a model to this shortcut function, the default manager 
     1777is used to execute the underlying ``get()`` query. If you don't want to 
     1778use the default manager, or if you want to search a list of related objects, 
     1779you can provide ``get_object_or_404()`` with a manager object instead. 
     1780For example:: 
     1781 
     1782    # Get the author of blog instance `e` with a name of 'Fred' 
     1783    a = get_object_or_404(e.authors, name='Fred') 
     1784 
     1785    # Use a custom manager 'recent_entries' in the search for an 
     1786    # entry with a primary key of 3 
     1787    e = get_object_or_404(Entry.recent_entries, pk=3) 
     1788 
     1789get_list_or_404() 
     1790----------------- 
     1791 
     1792``get_list_or_404`` behaves the same way as ``get_object_or_404()`` 
     1793-- except that it uses ``filter()`` instead of ``get()``. It raises 
     1794``Http404`` if the list is empty. 
     1795 
    17071796Falling back to raw SQL 
    17081797======================= 
     
    17231812about your database. 
    17241813 
    1725 .. _Executing custom SQL: http://www.djangoproject.com/documentation/model_api/#executing-custom-sql 
     1814.. _Executing custom SQL: ../model-api/#executing-custom-sql