Ticket #1464: db-api.patch

File db-api.patch, 17.1 KB (added by jbowtie@…, 9 years ago)

Probably needs more work but most of it should be sensible

  • docs/db-api.txt

     
    1010
    1111Throughout this reference, we'll refer to the following Poll application::
    1212
    13     class Poll(meta.Model):
    14         slug = meta.SlugField(unique_for_month='pub_date')
    15         question = meta.CharField(maxlength=255)
    16         pub_date = meta.DateTimeField()
    17         expire_date = meta.DateTimeField()
     13    class Poll(models.Model):
     14        slug = models.SlugField(unique_for_month='pub_date')
     15        question = models.CharField(maxlength=255)
     16        pub_date = models.DateTimeField()
     17        expire_date = models.DateTimeField()
    1818
    1919        def __repr__(self):
    2020            return self.question
    2121
    22     class Choice(meta.Model):
    23         poll = meta.ForeignKey(Poll, edit_inline=meta.TABULAR,
     22    class Choice(models.Model):
     23        poll = models.ForeignKey(Poll, edit_inline=meta.TABULAR,
    2424            num_in_admin=10, min_num_in_admin=5)
    25         choice = meta.CharField(maxlength=255, core=True)
    26         votes = meta.IntegerField(editable=False, default=0)
     25        choice = models.CharField(maxlength=255, core=True)
     26        votes = models.IntegerField(editable=False, default=0)
    2727
    2828        def __repr__(self):
    2929            return self.choice
     
    3333
    3434Each model exposes these module-level functions for lookups:
    3535
    36 get_object(\**kwargs)
     36get(\**kwargs)
    3737---------------------
    3838
    3939Returns the object matching the given lookup parameters, which should be in
     
    4141``*DoesNotExist`` exception if an object wasn't found for the given parameters.
    4242Raises ``AssertionError`` if more than one object was found.
    4343
    44 get_list(\**kwargs)
     44filter(\**kwargs)
    4545-------------------
    4646
    4747Returns a list of objects matching the given lookup parameters, which should be
    4848in the format described in "Field lookups" below. If no objects match the given
    49 parameters, it returns an empty list. ``get_list()`` will always return a list.
     49parameters, it returns an empty list. ``filter()`` will always return a list.
    5050
    5151get_iterator(\**kwargs)
    5252-----------------------
    5353
    54 Just like ``get_list()``, except it returns an iterator instead of a list. This
     54Just like ``filter()``, except it returns an iterator instead of a list. This
    5555is more efficient for large result sets. This example shows the difference::
    5656
    57     # get_list() loads all objects into memory.
    58     for obj in foos.get_list():
     57    # filter() loads all objects into memory.
     58    for obj in foos.filter():
    5959        print repr(obj)
    6060
    6161    # get_iterator() only loads a number of objects into memory at a time.
     
    7575get_values(\**kwargs)
    7676---------------------
    7777
    78 Just like ``get_list()``, except it returns a list of dictionaries instead of
     78Just like ``filter()``, except it returns a list of dictionaries instead of
    7979model-instance objects.
    8080
    8181It accepts an optional parameter, ``fields``, which should be a list or tuple
     
    8686``Poll`` model defined above::
    8787
    8888    >>> from datetime import datetime
    89     >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
     89    >>> p1 = Poll(slug='whatsup', question="What's up?",
    9090    ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
    9191    >>> p1.save()
    92     >>> p2 = polls.Poll(slug='name', question="What's your name?",
     92    >>> p2 = Poll(slug='name', question="What's your name?",
    9393    ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
    9494    >>> p2.save()
    95     >>> polls.get_list()
     95    >>> Poll.objects.all()
    9696    [What's up?, What's your name?]
    97     >>> polls.get_values()
     97    >>> Poll.objects.get_values()
    9898    [{'id': 1, 'slug': 'whatsup', 'question': "What's up?", 'pub_date': datetime.datetime(2005, 2, 20), 'expire_date': datetime.datetime(2005, 3, 20)},
    9999     {'id': 2, 'slug': 'name', 'question': "What's your name?", 'pub_date': datetime.datetime(2005, 3, 20), 'expire_date': datetime.datetime(2005, 4, 20)}]
    100     >>> polls.get_values(fields=['id', 'slug'])
     100    >>> Poll.objects.get_values(fields=['id', 'slug'])
    101101    [{'id': 1, 'slug': 'whatsup'}, {'id': 2, 'slug': 'name'}]
    102102
    103103Use ``get_values()`` when you know you're only going to need a couple of field
     
    110110Just like ``get_values()``, except it returns an iterator instead of a list.
    111111See the section on ``get_iterator()`` above.
    112112
    113 get_in_bulk(id_list, \**kwargs)
     113in_bulk(id_list, \**kwargs)
    114114-------------------------------
    115115
    116116Takes a list of IDs and returns a dictionary mapping each ID to an instance of
     
    119119example, using the ``Poll`` model defined above::
    120120
    121121    >>> from datetime import datetime
    122     >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
     122    >>> p1 = Poll(slug='whatsup', question="What's up?",
    123123    ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
    124124    >>> p1.save()
    125     >>> p2 = polls.Poll(slug='name', question="What's your name?",
     125    >>> p2 = Poll(slug='name', question="What's your name?",
    126126    ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
    127127    >>> p2.save()
    128     >>> polls.get_list()
     128    >>> Poll.objects.all()
    129129    [What's up?, What's your name?]
    130     >>> polls.get_in_bulk([1])
     130    >>> Poll.objects.in_bulk([1])
    131131    {1: What's up?}
    132     >>> polls.get_in_bulk([1, 2])
     132    >>> Poll.objects.in_bulk([1, 2])
    133133    {1: What's up?, 2: What's your name?}
    134134
    135135Field lookups
     
    138138Basic field lookups take the form ``field__lookuptype`` (that's a
    139139double-underscore). For example::
    140140
    141     polls.get_list(pub_date__lte=datetime.datetime.now())
     141    Poll.objects.filter(pub_date__lte=datetime.datetime.now())
    142142
    143143translates (roughly) into the following SQL::
    144144
    145     SELECT * FROM polls_polls WHERE pub_date <= NOW();
     145    SELECT * FROM polls_poll WHERE pub_date <= NOW();
    146146
    147147.. admonition:: How this is possible
    148148
     
    155155    ===========  ==============================================================
    156156    Type         Description
    157157    ===========  ==============================================================
    158     exact        Exact match: ``polls.get_object(id__exact=14)``.
     158    exact        Exact match: ``Poll.objects.get(id__exact=14)``.
    159159    iexact       Case-insensitive exact match:
    160                  ``polls.get_list(slug__iexact="foo")`` matches a slug of
     160                 ``Poll.objects.filter(slug__iexact="foo")`` matches a slug of
    161161                 ``foo``, ``FOO``, ``fOo``, etc.
    162162    contains     Case-sensitive containment test:
    163                  ``polls.get_list(question__contains="spam")`` returns all polls
     163                 ``Poll.objects.filter(question__contains="spam")`` returns all polls
    164164                 that contain "spam" in the question. (PostgreSQL and MySQL
    165165                 only. SQLite doesn't support case-sensitive LIKE statements;
    166166                 ``contains`` will act like ``icontains`` for SQLite.)
    167167    icontains    Case-insensitive containment test.
    168     gt           Greater than: ``polls.get_list(id__gt=4)``.
     168    gt           Greater than: ``Poll.objects.filter(id__gt=4)``.
    169169    gte          Greater than or equal to.
    170170    lt           Less than.
    171171    lte          Less than or equal to.
    172172    ne           Not equal to.
    173     in           In a given list: ``polls.get_list(id__in=[1, 3, 4])`` returns
     173    in           In a given list: ``Poll.objects.filter(id__in=[1, 3, 4])`` returns
    174174                 a list of polls whose IDs are either 1, 3 or 4.
    175175    startswith   Case-sensitive starts-with:
    176                  ``polls.get_list(question__startswith="Would")``. (PostgreSQL
     176                 ``Poll.objects.filter(question__startswith="Would")``. (PostgreSQL
    177177                 and MySQL only. SQLite doesn't support case-sensitive LIKE
    178178                 statements; ``startswith`` will act like ``istartswith`` for
    179179                 SQLite.)
     
    181181    istartswith  Case-insensitive starts-with.
    182182    iendswith    Case-insensitive ends-with.
    183183    range        Range test:
    184                  ``polls.get_list(pub_date__range=(start_date, end_date))``
     184                 ``Poll.objects.filter(pub_date__range=(start_date, end_date))``
    185185                 returns all polls with a pub_date between ``start_date``
    186186                 and ``end_date`` (inclusive).
    187187    year         For date/datetime fields, exact year match:
    188                  ``polls.get_count(pub_date__year=2005)``.
     188                 ``Poll.objects.count(pub_date__year=2005)``.
    189189    month        For date/datetime fields, exact month match.
    190190    day          For date/datetime fields, exact day match.
    191191    isnull       True/False; does is IF NULL/IF NOT NULL lookup:
    192                  ``polls.get_list(expire_date__isnull=True)``.
     192                 ``Poll.objects.filter(expire_date__isnull=True)``.
    193193    ===========  ==============================================================
    194194
    195195Multiple lookups are allowed, of course, and are translated as "AND"s::
    196196
    197     polls.get_list(
     197    Poll.objects.filter(
    198198        pub_date__year=2005,
    199199        pub_date__month=1,
    200200        question__startswith="Would",
     
    203203...retrieves all polls published in January 2005 that have a question starting with "Would."
    204204
    205205For convenience, there's a ``pk`` lookup type, which translates into
    206 ``(primary_key)__exact``. In the polls example, these two statements are
     206``(primary_key)``. In the polls example, these two statements are
    207207equivalent::
    208208
    209     polls.get_object(id__exact=3)
    210     polls.get_object(pk=3)
     209    Poll.objects.get(id=3)
     210    Poll.objects.get(pk=3)
    211211
    212212``pk`` lookups also work across joins. In the polls example, these two
    213213statements are equivalent::
    214214
    215     choices.get_list(poll__id__exact=3)
    216     choices.get_list(poll__pk=3)
     215    Choice.objects.filter(poll__id=3)
     216    Choice.objects.filter(poll__pk=3)
    217217
    218218If you pass an invalid keyword argument, the function will raise ``TypeError``.
    219219
     
    228228
    229229A ``Q`` object is an instance of ``django.core.meta.Q``, used to encapsulate a collection of
    230230keyword arguments. These keyword arguments are specified in the same way as keyword arguments to
    231 the basic lookup functions like get_object() and get_list(). For example::
     231the basic lookup functions like get() and filter(). For example::
    232232
    233233    Q(question__startswith='What')
    234234
     
    247247``Q`` object arguments are provided to a lookup function, they will be "AND"ed together.
    248248For example::
    249249
    250     polls.get_object(
     250    Poll.objects.get(
    251251        Q(question__startswith='Who'),
    252         Q(pub_date__exact=date(2005, 5, 2)) | Q(pub_date__exact=date(2005, 5, 6))
     252        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    253253    )
    254254
    255255... roughly translates into the SQL::
     
    262262However, if a ``Q`` object is provided, it must precede the definition of any keyword arguments.
    263263For example::
    264264
    265     polls.get_object(
    266         Q(pub_date__exact=date(2005, 5, 2)) | Q(pub_date__exact=date(2005, 5, 6)),
     265    Poll.objects.get(
     266        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    267267        question__startswith='Who')
    268268
    269269... would be a valid query, equivalent to the previous example; but::
    270270
    271271    # INVALID QUERY
    272     polls.get_object(
     272    Poll.objects.get(
    273273        question__startswith='Who',
    274         Q(pub_date__exact=date(2005, 5, 2)) | Q(pub_date__exact=date(2005, 5, 6)))
     274        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))
    275275
    276276... would not be valid.
    277277
    278278A ``Q`` objects can also be provided to the ``complex`` keyword argument. For example::
    279279
    280     polls.get_object(
     280    Poll.objects.get(
    281281        complex=Q(question__startswith='Who') &
    282             (Q(pub_date__exact=date(2005, 5, 2)) |
    283              Q(pub_date__exact=date(2005, 5, 6))
     282            (Q(pub_date=date(2005, 5, 2)) |
     283             Q(pub_date=date(2005, 5, 6))
    284284        )
    285285    )
    286286
     
    295295``ordering`` key in the model, but the ordering may be explicitly
    296296provided by the ``order_by`` argument to a lookup::
    297297
    298     polls.get_list(
     298    Poll.objects.filter(
    299299        pub_date__year=2005,
    300300        pub_date__month=1,
    301301        order_by=('-pub_date', 'question'),
     
    306306descending order. Ascending order is implied. To order randomly, use "?", like
    307307so::
    308308
    309     polls.get_list(order_by=['?'])
     309    Poll.objects.filter(order_by=['?'])
    310310
    311311To order by a field in a different table, add the other table's name and a dot,
    312312like so::
    313313
    314     choices.get_list(order_by=('polls.pub_date', 'choice'))
     314    Choice.objects.filter(order_by=('Poll.pub_date', 'choice'))
    315315
    316316There's no way to specify whether ordering should be case sensitive. With
    317317respect to case-sensitivity, Django will order results however your database
     
    321321=====================
    322322
    323323Joins may implicitly be performed by following relationships:
    324 ``choices.get_list(poll__slug__exact="eggs")`` fetches a list of ``Choice``
     324``Choice.objects.filter(poll__slug="eggs")`` fetches a list of ``Choice``
    325325objects where the associated ``Poll`` has a slug of ``eggs``.  Multiple levels
    326326of joins are allowed.
    327327
    328328Given an instance of an object, related objects can be looked-up directly using
    329329convenience functions. For example, if ``p`` is a ``Poll`` instance,
    330 ``p.get_choice_list()`` will return a list of all associated choices. Astute
     330``p.choice_set.all()`` will return a list of all associated choices. Astute
    331331readers will note that this is the same as
    332 ``choices.get_list(poll__id__exact=p.id)``, except clearer.
     332``Choice.objects.filter(poll__id=p.id)``, except clearer.
    333333
    334334Each type of relationship creates a set of methods on each object in the
    335335relationship. These methods are created in both directions, so objects that are
     
    342342Each object in a one-to-one relationship will have a ``get_relatedobjectname()``
    343343method. For example::
    344344
    345     class Place(meta.Model):
     345    class Place(models.Model):
    346346        # ...
    347347
    348     class Restaurant(meta.Model):
     348    class Restaurant(models.Model):
    349349        # ...
    350         the_place = meta.OneToOneField(places.Place)
     350        the_place = models.OneToOneField(Place)
    351351
    352352In the above example, each ``Place`` will have a ``get_restaurant()`` method,
    353353and each ``Restaurant`` will have a ``get_the_place()`` method.
     
    359359``get_relatedobject()`` method, and the related-to object will have
    360360``get_relatedobject()``, ``get_relatedobject_list()``, and
    361361``get_relatedobject_count()`` methods (the same as the module-level
    362 ``get_object()``, ``get_list()``, and ``get_count()`` methods).
     362``get_object()``, ``filter()``, and ``get_count()`` methods).
    363363
    364364In the poll example above, here are the available choice methods on a ``Poll`` object ``p``::
    365365
     
    399399
    400400For example, using the Poll and Choice models from above, if you do the following::
    401401
    402     c = choices.get_object(id__exact=5, select_related=True)
     402    c = Choice.objects.get(id=5, select_related=True)
    403403
    404404Then subsequent calls to ``c.get_poll()`` won't hit the database.
    405405
    406406Note that ``select_related`` follows foreign keys as far as possible. If you have the
    407407following models::
    408408
    409     class Poll(meta.Model):
     409    class Poll(models.Model):
    410410        # ...
    411411
    412     class Choice(meta.Model):
     412    class Choice(models.Model):
    413413        # ...
    414         poll = meta.ForeignKey(Poll)
     414        poll = models.ForeignKey(Poll)
    415415
    416416    class SingleVote(meta.Model):
    417417        # ...
    418         choice = meta.ForeignKey(Choice)
     418        choice = models.ForeignKey(Choice)
    419419
    420 then a call to ``singlevotes.get_object(id__exact=4, select_related=True)`` will
     420then a call to ``singlevotes.get_object(id=4, select_related=True)`` will
    421421cache the related choice *and* the related poll::
    422422
    423     >>> sv = singlevotes.get_object(id__exact=4, select_related=True)
     423    >>> sv = singlevotes.get_object(id=4, select_related=True)
    424424    >>> c = sv.get_choice()        # Doesn't hit the database.
    425425    >>> p = c.get_poll()           # Doesn't hit the database.
    426426
    427     >>> sv = singlevotes.get_object(id__exact=4) # Note no "select_related".
     427    >>> sv = singlevotes.get_object(id=4) # Note no "select_related".
    428428    >>> c = sv.get_choice()        # Hits the database.
    429429    >>> p = c.get_poll()           # Hits the database.
    430430
     
    465465dictionary mapping attribute names to a SQL clause to use to calculate that
    466466attribute. For example::
    467467
    468     polls.get_list(
     468    Poll.objects.filter(
    469469        select={
    470470            'choice_count': 'SELECT COUNT(*) FROM choices WHERE poll_id = polls.id'
    471471        }
     
    488488
    489489For example::
    490490
    491     polls.get_list(question__startswith='Who', where=['id IN (3, 4, 5, 20)'])
     491    Poll.objects.filter(question__startswith='Who', where=['id IN (3, 4, 5, 20)'])
    492492
    493493...translates (roughly) into the following SQL:
    494494
     
    512512Creating new objects (i.e. ``INSERT``) is done by creating new instances
    513513of objects then calling save() on them::
    514514
    515     >>> p = polls.Poll(slug="eggs",
     515    >>> p = Poll(slug="eggs",
    516516    ...                question="How do you like your eggs?",
    517517    ...                pub_date=datetime.datetime.now(),
    518518    ...                expire_date=some_future_date)
     
    532532
    533533Each of those ``add_choice`` methods is equivalent to (but much simpler than)::
    534534
    535     >>> c = polls.Choice(poll_id=p.id, choice="Over easy", votes=0)
     535    >>> c = Choice(poll_id=p.id, choice="Over easy", votes=0)
    536536    >>> c.save()
    537537
    538538Note that when using the `add_foo()`` methods, you do not give any value
Back to Top