Django

Code

Changeset 2706

Show
Ignore:
Timestamp:
04/17/06 01:43:41 (3 years ago)
Author:
russellm
Message:

magic-removal: Completed review of db-api documentation.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/magic-removal/docs/db-api.txt

    r2697 r2706  
    4747================ 
    4848 
    49 Querying in Django is based upon the construction and evaluation of Query Sets.  
    50  
    51 A Query Set is a database-independent representation of a query. It can be  
    52 thought of as a representation of a group of objects that meet a given set  
    53 of criteria. However, the members of the set are not determined until the  
    54 Query Set is formally evaluated. 
    55  
    56 To compose a Query using Django, you obtain an initial a Query Set. This  
    57 Query Set can then be refined using a range of operations. When you have 
    58 a Query Set that meets your needs, it can be evaluated (using iterators, slicing, 
    59 or one of a range of other techniques), yielding an object or list of objects 
    60 that meet the specifications of the Query Set. 
    61  
    62 Obtaining a Query Set 
    63 ===================== 
    64  
    65 Query Sets are obtained using the Manager object on a model. Every model  
    66 has at least one Manager; by default, the Manager is called ``objects``. 
     49Querying in Django is based upon the construction and evaluation of Query  
     50Sets.  
     51 
     52A Query Set is a database-independent representation of a group of objects  
     53that all meet a given set of criteria. However, the determination of which  
     54objects are actually members of the Query Set is not made until you formally 
     55evaluate the Query Set. 
     56 
     57To construct a Query Set that meets your requirements, you start by obtaining 
     58an initial Query Set that describes all objects of a given type. This initial  
     59Query Set can then be refined using a range of operations. Once you have  
     60refined your Query Set to the point where it describes the group of objects  
     61you require, it can be evaluated (using iterators, slicing, or one of a range  
     62of other techniques), yielding an object or list of objects that meet the  
     63specifications of the Query Set. 
     64 
     65Obtaining an Initial Query Set 
     66============================== 
     67 
     68Every model has at least one Manager; by default, the Manager is called  
     69``objects``. One of the most important roles of the Manager is as a source  
     70of initial Query Sets. The Manager acts as a Query Set that describes all  
     71objects of the type being managed; ``Polls.objects`` is the initial Query Set  
     72that contains all Polls in the database. 
     73 
     74The initial Query Set on the Manager behaves in the same way as every other  
     75Query Set in every respect except one - it cannot be evaluated. To overcome  
     76this limitation, the Manager Query Set has an ``all()`` method. The ``all()`` 
     77method produces a copy of the initial Query Set - a copy that *can* be  
     78evaluated:: 
     79 
     80    all_polls = Poll.objects.all() 
    6781 
    6882See the `Managers`_ section of the Model API for more details on the role  
     
    7185.. _Managers: http://www.djangoproject.com/documentation/model_api/#managers 
    7286 
    73 The manager has a special factory method for creating Query Sets:: 
    74  
    75     queryset = Poll.objects.all() 
    76  
    77 This creates a new Query Set that matches all the objects of the given class. 
    78  
    79 As a convenient shortcut, all of these Query Set construction methods  
    80 can be accessed from the Manager object itself. 
    81 The following two queries are identical:: 
    82  
    83     Poll.objects.all().filter(question__startswith="What") 
    84     Poll.objects.filter(question__startswith="What") 
    85  
    86  
    8787Query Set Refinement 
    8888==================== 
    8989 
    90 The default Query Set returned by the Manager contains all objects of the 
    91 Model type. In order to be useful,  
    92  
    93 Any Query Set can be refined by calling one of the following methods: 
    94  
    95 filter(\**kwargs) 
     90The initial Query Set provided by the Manager describes all objects of a  
     91given type. However, you will usually need to describe a subset of the  
     92complete set of objects.  
     93 
     94To create such a subset, you refine the initial Query Set, adding conditions 
     95until you have described a set that meets your needs. The two most common  
     96mechanisms for refining a Query Set are: 
     97 
     98``filter(**kwargs)`` 
    9699    Returns a new Query Set containing objects that match the given lookup parameters.  
    97100 
    98 exclude(\**kwargs) 
     101``exclude(**kwargs)`` 
    99102    Return a new Query Set containing objects that do not match the given lookup parameters. 
    100103 
    101104Lookup parameters should be in the format described in "Field lookups" below.  
    102105 
    103 Query Set refinements can be chained together:: 
    104  
    105     Poll.objects.filter(question__startswith="What").exclude().filter(...) 
    106  
    107 Query Sets can also be stored and reused:: 
    108  
    109     q1 = Poll.objects.filter() 
    110     q2 = q1.exclude() 
    111     q3 = q1.filter() 
     106The result of refining a Query Set is itself a Query Set; so it is possible to 
     107chain refinements together. For example:: 
     108 
     109    Poll.objects.filter( 
     110        question__startswith="What").exclude( 
     111            pub_date__gte=datetime.now()).filter( 
     112                pub_date__gte=datetime(2005,1,1)) 
     113 
     114...takes the initial Query Set, and adds a filter, then an exclusion, then  
     115another filter to remove elements present in the initial Query Set. The  
     116final result is a Query Set containing all Polls with a question that  
     117starts with "What", that were published between 1 Jan 2005 and today. 
     118 
     119Each Query Set is a unique object. The process of refinement is not one 
     120of adding a condition to the initial Query Set. Rather, each refinement  
     121creates a separate and distinct Query Set that can be stored, used. and  
     122reused. For example:: 
     123 
     124    q1 = Poll.objects.filter(question__startswith="What") 
     125    q2 = q1.exclude(pub_date__gte=datetime.now()) 
     126    q3 = q1.filter(pub_date__gte=datetime.now()) 
     127 
     128will construct 3 Query Sets; a base query set containing all Polls with a  
     129question that starts with "What", and two subsets of the base Query Set (one 
     130with an exlusion, one with a filter). The initial Query Set is unaffected by  
     131the refinement process. 
     132 
     133It should be noted that the construction of a Query Set does not involve any 
     134activity on the database. The database is not consulted until a Query Set is  
     135evaluated. 
    112136 
    113137Field lookups 
     
    117141double-underscore). For example:: 
    118142 
    119     Poll.objects.filter(pub_date__lte=datetime.datetime.now()) 
     143    Poll.objects.filter(pub_date__lte=datetime.now()) 
    120144 
    121145translates (roughly) into the following SQL:: 
     
    177201    Poll.objects.get(id__exact=14) 
    178202 
    179 Multiple lookups are also allowed. When separated by commans, the list of lookups will be 
    180 "AND"ed together:: 
     203Multiple lookup parameters are allowed. When separated by commans, the list of  
     204lookup parameters will be "AND"ed together:: 
    181205 
    182206    Poll.objects.filter( 
     
    206230.. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000 
    207231 
     232OR lookups 
     233========== 
     234 
     235Keyword argument queries are "AND"ed together. If you have more  
     236complex query requirements (for example, you need to include an ``OR``  
     237statement in your query), you need to use ``Q`` objects. 
     238 
     239A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a  
     240collection of keyword arguments. These keyword arguments are specified in  
     241the same way as keyword arguments to the basic lookup functions like get()  
     242and filter(). For example:: 
     243 
     244    Q(question__startswith='What') 
     245 
     246is a ``Q`` object encapsulating a single ``LIKE`` query. ``Q`` objects can be  
     247combined using the ``&`` and ``|`` operators. When an operator is used on two  
     248``Q`` objects, it yields a new ``Q`` object. For example the statement:: 
     249 
     250    Q(question__startswith='Who') | Q(question__startswith='What') 
     251 
     252... yields a single ``Q`` object that represents the "OR" of two  
     253"question__startswith" queries, equivalent to the SQL WHERE clause:: 
     254 
     255    ... WHERE question LIKE 'Who%' OR question LIKE 'What%' 
     256 
     257You can compose statements of arbitrary complexity by combining ``Q`` objects  
     258with the ``&`` and ``|`` operators. Parenthetical grouping can also be used. 
     259 
     260One or more ``Q`` objects can then provided as arguments to the lookup  
     261functions. If multiple ``Q`` object arguments are provided to a lookup  
     262function, they will be "AND"ed together. For example:: 
     263 
     264    Poll.objects.get( 
     265        Q(question__startswith='Who'), 
     266        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) 
     267    ) 
     268 
     269... roughly translates into the SQL:: 
     270 
     271    SELECT * from polls WHERE question LIKE 'Who%' 
     272        AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06') 
     273 
     274If necessary, lookup functions can mix the use of ``Q`` objects and keyword  
     275arguments. All arguments provided to a lookup function (be they keyword  
     276argument or ``Q`` object) are "AND"ed together. However, if a ``Q`` object is  
     277provided, it must precede the definition of any keyword arguments. For  
     278example:: 
     279 
     280    Poll.objects.get( 
     281        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)), 
     282        question__startswith='Who') 
     283 
     284... would be a valid query, equivalent to the previous example; but:: 
     285 
     286    # INVALID QUERY 
     287    Poll.objects.get( 
     288        question__startswith='Who', 
     289        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))) 
     290 
     291... would not be valid. 
     292 
     293A ``Q`` objects can also be provided to the ``complex`` keyword argument. For example:: 
     294 
     295    Poll.objects.get( 
     296        complex=Q(question__startswith='Who') & 
     297            (Q(pub_date=date(2005, 5, 2)) | 
     298             Q(pub_date=date(2005, 5, 6)) 
     299        ) 
     300    ) 
     301 
     302See the `OR lookups examples page`_ for more examples. 
     303 
     304.. _OR lookups examples page: http://www.djangoproject.com/documentation/models/or_lookups/ 
     305 
    208306Query Set evaluation 
    209307==================== 
    210308 
    211 Once you have constructed a Query Set to meet your needs, it must be evaluated 
    212 to return the objects that are contained in the set. This can be achieved in  
    213  
    214 A Query Set is an iterable object:: 
    215  
    216     queryset = Poll.objects.all() 
    217     for p in queryset
     309A Query Set must be evaluated to return the objects that are contained in the  
     310set. This can be achieved by iteration, slicing, or by specialist function. 
     311 
     312A Query Set is an iterable object. Therefore, it can be used in loop 
     313constructs. For example:: 
     314 
     315    for p in Poll.objects.all()
    218316        print p 
    219317         
    220 Query Sets can also be sliced:: 
    221  
    222     fifth_poll = queryset[4] 
    223     all_polls_but_the_first_two = queryset[2:] 
    224  
    225  
    226 If you really need to have a . :: 
     318will print all the Poll objects, using the ``__repr__()`` method of Poll. 
     319         
     320A Query Set can also be sliced, using array notation:: 
     321 
     322    fifth_poll = Poll.objects.all()[4] 
     323    all_polls_but_the_first_two = Poll.objects.all()[2:] 
     324    every_second_poll = Poll.objects.all()[::2] 
     325 
     326Query Sets are lazy objects - that is, they are not *actually* sets (or  
     327lists) that contain all the objects that they represent. Python protocol 
     328magic is used to make the Query Set *look* like an iterable, sliceable 
     329object, but behind the scenes, Django is using caching to only instantiate 
     330objects as they are required. 
     331 
     332If you really need to have a list, you can force the evaluation of the 
     333lazy object:: 
     334 
    227335    querylist = list(Poll.objects.all()) 
    228336 
    229 However - be warned; if you use these approaches,  
    230  
    231 Regardless of whether you iterate or slice the Query Set,  
    232  
    233 upon first evaluation, the query will be executed on the database, and the results cached. 
    234 Subsequent evaluations of the Query Set reuse the cached results.  
    235  
    236 As an alternative to iteration and slicing, you can use one of the  
    237 following functions. These functions do not populate or effect the cache: 
    238  
    239 get(\**kwargs) 
    240 -------------- 
     337However - be warned; this could have a large memory overhead, as Django will 
     338create an in-memory representation of every element of the list. 
     339 
     340Caching and Query Sets 
     341====================== 
     342 
     343Each Query Set contains a cache. In a newly created Query Set, this cache  
     344is unpopulated. When a Query Set is evaluated for the first time, Django  
     345makes a database query to populate the cache, and then returns the results  
     346that have been explicitly requested (e.g., the next element if iteration  
     347is in use). Subsequent evaluations of the Query Set reuse the cached results. 
     348 
     349This caching behavior must be kept in mind when using Query Sets. For  
     350example, the following will cause two temporary Query Sets to be created, 
     351evaluated, and thrown away:: 
     352 
     353    print [p for p in Poll.objects.all()] # Evaluate the Query Set 
     354    print [p for p in Poll.objects.all()] # Evaluate the Query Set again 
     355 
     356On a small, low-traffic website, this may not pose a serious problem. However, 
     357on a high traffic website, it effectively doubles your database load. In  
     358addition, there is a possibility that the two lists may not be identical,  
     359since a poll may be added or deleted by another user between making the two  
     360requests.  
     361 
     362To avoid this problem, simply save the Query Set and reuse it:: 
     363 
     364    queryset = Poll.objects.all() 
     365    print [p for p in queryset] # Evaluate the query set 
     366    print [p for p in queryset] # Re-use the cache from the evaluation 
     367 
     368Specialist Query Set Evaluation 
     369=============================== 
     370 
     371The following specialist functions can also be used to evaluate a Query Set.  
     372Unlike iteration or slicing, these methods do not populate the cache; each  
     373time one of these evaluation functions is used, the database will be queried.  
     374 
     375``get(**kwargs)`` 
     376----------------- 
    241377 
    242378Returns the object matching the given lookup parameters, which should be in 
     
    245381Raises ``AssertionError`` if more than one object was found. 
    246382 
    247 count() 
    248 ------- 
     383``count()`` 
     384----------- 
    249385 
    250386Returns an integer representing the number of objects in the database matching 
     
    254390return a long integer instead of a normal Python integer. 
    255391 
    256 in_bulk(id_list) 
    257 ---------------- 
     392``in_bulk(id_list)`` 
     393-------------------- 
    258394 
    259395Takes a list of IDs and returns a dictionary mapping each ID to an instance of 
     
    267403    {} 
    268404 
    269 latest(field_name=None) 
    270 ----------------------- 
     405``latest(field_name=None)`` 
     406--------------------------- 
    271407 
    272408Returns the latest object, according to the model's 'get_latest_by' 
     
    278414    What's your name? 
    279415 
    280 OR lookups 
    281 ========== 
    282  
    283 By default, keyword argument queries are "AND"ed together. If you have more  
    284 complex query requirements (for example, you need to include an ``OR``  
    285 statement in your query), you need to use ``Q`` objects. 
    286  
    287 A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a  
    288 collection of keyword arguments. These keyword arguments are specified in  
    289 the same way as keyword arguments to the basic lookup functions like get()  
    290 and filter(). For example:: 
    291  
    292     Q(question__startswith='What') 
    293  
    294 is a ``Q`` object encapsulating a single ``LIKE`` query. ``Q`` objects can be  
    295 combined using the ``&`` and ``|`` operators. When an operator is used on two  
    296 ``Q`` objects, it yields a new ``Q`` object. For example the statement:: 
    297  
    298     Q(question__startswith='Who') | Q(question__startswith='What') 
    299  
    300 ... yields a single ``Q`` object that represents the "OR" of two "question__startswith" queries, equivalent to the SQL WHERE clause:: 
    301  
    302     ... WHERE question LIKE 'Who%' OR question LIKE 'What%' 
    303  
    304 You can compose statements of arbitrary complexity by combining ``Q`` objects with the ``&`` and ``|`` operators. Parenthetical grouping can also be used. 
    305  
    306 One or more ``Q`` objects can then provided as arguments to the lookup functions. If multiple 
    307 ``Q`` object arguments are provided to a lookup function, they will be "AND"ed together. 
    308 For example:: 
    309  
    310     Poll.objects.get( 
    311         Q(question__startswith='Who'), 
    312         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) 
    313     ) 
    314  
    315 ... roughly translates into the SQL:: 
    316  
    317     SELECT * from polls WHERE question LIKE 'Who%' 
    318         AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06') 
    319  
    320 If necessary, lookup functions can mix the use of ``Q`` objects and keyword arguments. All arguments 
    321 provided to a lookup function (be they keyword argument or ``Q`` object) are "AND"ed together. 
    322 However, if a ``Q`` object is provided, it must precede the definition of any keyword arguments. 
    323 For example:: 
    324  
    325     Poll.objects.get( 
    326         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)), 
    327         question__startswith='Who') 
    328  
    329 ... would be a valid query, equivalent to the previous example; but:: 
    330  
    331     # INVALID QUERY 
    332     Poll.objects.get( 
    333         question__startswith='Who', 
    334         Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))) 
    335  
    336 ... would not be valid. 
    337  
    338 A ``Q`` objects can also be provided to the ``complex`` keyword argument. For example:: 
    339  
    340     Poll.objects.get( 
    341         complex=Q(question__startswith='Who') & 
    342             (Q(pub_date=date(2005, 5, 2)) | 
    343              Q(pub_date=date(2005, 5, 6)) 
    344         ) 
    345     ) 
    346  
    347 See the `OR lookups examples page`_ for more examples. 
    348  
    349 .. _OR lookups examples page: http://www.djangoproject.com/documentation/models/or_lookups/ 
    350  
    351  
    352416Relationships (joins) 
    353417===================== 
    354418 
    355 Joins may implicitly be performed by following relationships: 
    356 ``Choice.objects.filter(poll__slug="eggs")`` fetches a list of ``Choice`` 
    357 objects where the associated ``Poll`` has a slug of ``eggs``.  Multiple levels 
    358 of joins are allowed. 
    359  
    360 Given an instance of an object, related objects can be looked-up directly using 
    361 convenience functions. For example, if ``p`` is a ``Poll`` instance, 
    362 ``p.choice_set.all()`` will return a list of all associated choices. Astute 
    363 readers will note that this is the same as 
    364 ``Choice.objects.filter(poll__id=p.id)``, except clearer. 
    365  
    366 Each type of relationship creates a set of methods on each object in the 
    367 relationship. These methods are created in both directions, so objects that are 
    368 "related-to" need not explicitly define reverse relationships; that happens 
    369 automatically. 
    370  
    371 One-to-one relations 
    372 -------------------- 
    373  
    374 Each object in a one-to-one relationship will have a ``get_relatedobjectname()`` 
    375 method. For example:: 
    376  
    377     class Place(models.Model): 
    378         # ... 
    379  
    380     class Restaurant(models.Model): 
    381         # ... 
    382         the_place = models.OneToOneField(Place) 
    383  
    384 In the above example, each ``Place`` will have a ``get_restaurant()`` method, 
    385 and each ``Restaurant`` will have a ``get_the_place()`` method. 
    386  
    387 Many-to-one relations 
     419When you define a relationship in a model (i.e., a ForeignKey,  
     420OneToOneField, or ManyToManyField), Django uses the name of the 
     421relationship to add a descriptor_ on every instance of the model. 
     422This descriptor behaves just like a normal attribute, providing 
     423access to the related object or objects.  For example,  
     424``mychoice.poll`` will return the poll object associated with a specific  
     425instance of ``Choice``. 
     426 
     427.. _descriptor: http://users.rcn.com/python/download/Descriptor.htm 
     428 
     429Django also adds a descriptor for the 'other' side of the relationship - 
     430the link from the related model to the model that defines the relationship. 
     431Since the related model has no explicit reference to the source model,  
     432Django will automatically derive a name for this descriptor. The name that  
     433Django chooses depends on the type of relation that is represented. However,  
     434if the definition of the relation has a `related_name` parameter, Django 
     435will use this name in preference to deriving a name. 
     436 
     437There are two types of descriptor that can be employed: Single Object  
     438Descriptors and Object Set Descriptors. The following table describes  
     439when each descriptor type is employed. The local model is the model on  
     440which the relation is defined; the related model is the model referred  
     441to by the relation. 
     442 
     443    =============== ============= ============= 
     444    Relation Type   Local Model   Related Model 
     445    =============== ============= ============= 
     446    OneToOneField   Single Object Single Object 
     447     
     448    ForeignKey      Single Object Object Set 
     449         
     450    ManyToManyField Object Set    Object Set 
     451    =============== ============= ============= 
     452 
     453Single Object Descriptor 
     454------------------------ 
     455 
     456If the related object is a single object, the descriptor acts 
     457just as if the related object were an attribute:: 
     458 
     459    # Obtain the existing poll 
     460    old_poll = mychoice.poll 
     461    # Set a new poll 
     462    mychoice.poll = new_poll 
     463    # Save the change 
     464    mychoice.save() 
     465 
     466Whenever a change is made to a Single Object Descriptor, save()  
     467must be called to commit the change to the database. 
     468 
     469If no `related_name` parameter is defined, Django will use the  
     470lower case version of the source model name as the name for the 
     471related descriptor. For example, if the ``Choice`` model had  
     472a field:: 
     473     
     474    coordinator = models.OneToOneField(User) 
     475     
     476... instances of the model ``User`` would be able to call: 
     477 
     478    old_choice = myuser.choice 
     479    myuser.choice = new_choice 
     480 
     481By default, relations do not allow values of None; if you attempt 
     482to assign None to a Single Object Descriptor, an AttributeError 
     483will be thrown. However, if the relation has 'null=True' set  
     484(i.e., the database will allow NULLs for the relation), None can  
     485be assigned and returned by the descriptor to represent empty 
     486relations. 
     487 
     488Access to Single Object Descriptors is cached. The first time 
     489a descriptor on an instance is accessed, the database will be 
     490queried, and the result stored. Subsequent attempts to access  
     491the descriptor on the same instance will use the cached value. 
     492 
     493Object Set Descriptor 
    388494--------------------- 
    389495 
    390 In each many-to-one relationship, the related object will have a 
    391 ``get_relatedobject()`` method, and the related-to object will have 
    392 ``get_relatedobject()``, ``get_relatedobject_list()``, and 
    393 ``get_relatedobject_count()`` methods (the same as the module-level 
    394 ``get_object()``, ``filter()``, and ``get_count()`` methods). 
    395  
    396 In the poll example above, here are the available choice methods on a ``Poll`` object ``p``:: 
    397  
    398     p.get_choice() 
    399     p.get_choice_list() 
    400     p.get_choice_count() 
    401  
    402 And a ``Choice`` object ``c`` has the following method:: 
    403  
    404     c.get_poll() 
    405  
    406 Many-to-many relations 
    407 ---------------------- 
    408  
    409 Many-to-many relations result in the same set of methods as `Many-to-one relations`_, 
    410 except that the ``get_relatedobject_list()`` function on the related object will 
    411 return a list of instances instead of a single instance.  So, if the relationship 
    412 between ``Poll`` and ``Choice`` was many-to-many, ``choice.get_poll_list()`` would 
    413 return a list. 
    414  
    415 Specialist Query Sets  
    416 ===================== 
     496An Object Set Descriptor acts just like the Manager - as an initial Query  
     497Set describing the set of objects related to an instance. As such, any 
     498query refining technique (filter, exclude, etc) can be used on the Object  
     499Set descriptor. This also means that Object Set Descriptor cannot be evaluated 
     500directly - the ``all()`` method must be used to produce a Query Set that 
     501can be evaluated. 
     502 
     503If no ``related_name`` parameter is defined, Django will use the lower case  
     504version of the source model name appended with `_set` as the name for the  
     505related descriptor. For example, every ``Poll`` object has a ``choice_set``  
     506descriptor. 
     507 
     508The Object Set Descriptor has utility methods to add objects to the  
     509related object set: 
     510 
     511``add(obj1, obj2, ...)`` 
     512    Add the specified objects to the related object set.  
     513     
     514``create(\**kwargs)`` 
     515    Create a new object, and put it in the related object set. See  
     516    _`Creating new objects` 
     517 
     518The Object Set Descriptor may also have utility methods to remove objects 
     519from the related object set: 
     520 
     521``remove(obj1, obj2, ...)`` 
     522    Remove the specified objects from the related object set.  
     523     
     524``clear()`` 
     525    Remove all objects from the related object set. 
     526     
     527These two removal methods will not exist on ForeignKeys where ``Null=False``  
     528(such as in the Poll example). This is to prevent database inconsistency - if 
     529the related field cannot be set to None, then an object cannot be removed 
     530from one relation without adding it to another.   
     531 
     532The members of a related object set can be assigned from any iterable object. 
     533For example:: 
     534 
     535    mypoll.choice_set = [choice1, choice2] 
     536 
     537If the ``clear()`` method is available, any pre-existing objects will be removed 
     538from the Object Set before all objects in the iterable (in this case, a list)  
     539are added to the choice set. If the ``clear()`` method is not available, all  
     540objects in the iterable will be added without removing any existing elements.  
     541 
     542Each of these operations on the Object Set Descriptor has immediate effect 
     543on the database - every add, create and remove is immediately and 
     544automatically saved to the database.  
     545 
     546Relationships and Queries 
     547========================= 
     548 
     549When composing a ``filter`` or ``exclude`` refinement, it may be necessary to 
     550include conditions that span relationships. Relations can be followed as deep  
     551as required - just add descriptor names, separated by double underscores, to  
     552describe the full path to the query attribute. The query:: 
     553 
     554    Foo.objects.filter(name1__name2__name3__attribute__lookup=value) 
     555 
     556... is interpreted as 'get every Foo that has a name1 that has a name2 that 
     557has a name3 that has an attribute with lookup matching value'. In the Poll  
     558example:: 
     559 
     560    Choice.objects.filter(poll__slug__startswith="eggs") 
     561 
     562... describes the set of choices for which the related poll has a slug  
     563attribute that starts with "eggs". Django automatically composes the joins  
     564and conditions required for the SQL query. 
     565 
     566Specialist Query Sets Refinement  
     567================================ 
    417568 
    418569In addition to ``filter`` and ``exclude()``, Django provides a range of  
     
    420571the Query Set, or modify the way the SQL query is executed on the database. 
    421572 
    422 order_by(\*fields) 
    423 ------------------ 
     573``order_by(*fields)`` 
     574---------------------- 
    424575 
    425576The results returned by a Query Set are automatically ordered by the ordering  
     
    446597backend normally orders them. 
    447598 
    448 distinct() 
    449 ---------- 
     599``distinct()`` 
     600-------------- 
    450601 
    451602By default, a Query Set will not eliminate duplicate rows. This will not  
     
    458609SQL clause.  
    459610 
    460 values(\*fields) 
    461 ---------------- 
     611``values(*fields)`` 
     612-------------------- 
    462613 
    463614Returns a Values Query Set - a Query Set that evaluates to a list of  
     
    487638the fields you need to use. 
    488639 
    489 dates(field, kind, order='ASC') 
    490 ------------------------------- 
     640``dates(field, kind, order='ASC')`` 
     641----------------------------------- 
    491642 
    492643Returns a Date Query Set - a Query Set that evaluates to a list of  
     
    521672    [datetime.datetime(2005, 3, 20)] 
    522673 
    523 select_related() 
    524 ---------------- 
     674``select_related()`` 
     675-------------------- 
    525676 
    526677Relations are the bread and butter of databases, so there's an option to "follow" 
     
    562713 
    563714 
    564 extra(params, select, where, tables) 
    565 ------------------------------------ 
     715``extra(params, select, where, tables)`` 
     716---------------------------------------- 
    566717 
    567718Sometimes, the Django query syntax by itself isn't quite enough. To cater for these 
     
    706857====================== 
    707858 
    708 In addition to ``save()``, ``delete()`` and all of the ``add_*`` and ``get_*`` 
    709 related-object methods, a model object might get any or all of the following 
    710 methods: 
     859In addition to ``save()``, ``delete()``, a model object might get any or all  
     860of the following methods: 
    711861 
    712862get_FOO_display() 
     
    742892methods, where ``FOO`` is the name of the field. This returns the next and 
    743893previous object with respect to the date field, raising the appropriate 
    744 ``*DoesNotExist`` exception when appropriate. 
     894``DoesNotExist`` exception when appropriate. 
    745895 
    746896Both methods accept optional keyword arguments, which should be in the format