Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Beefed up docs/db-api.txt, adding a section for each automatic module…

…-level API function -- and optional ones, too

git-svn-id: http://code.djangoproject.com/svn/django/trunk@688 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit c2e42e1c5c11b45b8136aff36065cb879d12862c 1 parent 68c0742
Adrian Holovaty authored September 25, 2005

Showing 1 changed file with 243 additions and 14 deletions. Show diff stats Hide diff stats

  1. 257  docs/db-api.txt
257  docs/db-api.txt
@@ -2,9 +2,9 @@
2 2
 Database API reference
3 3
 ======================
4 4
 
5  
-Once you've created your `data models`_, you'll need to lookup data from the
6  
-database.  This document explains the database abstraction API derived from the
7  
-models, and how to create, retrieve, and update objects.
  5
+Once you've created your `data models`_, you'll need to retrieve data from the
  6
+database. This document explains the database abstraction API derived from the
  7
+models, and how to create, retrieve and update objects.
8 8
 
9 9
 .. _`data models`: http://www.djangoproject.com/documentation/model_api/
10 10
 
@@ -16,20 +16,121 @@ Throughout this reference, we'll refer to the following Poll application::
16 16
         pub_date = meta.DateTimeField()
17 17
         expire_date = meta.DateTimeField()
18 18
 
  19
+        def __repr__(self):
  20
+            return self.question
  21
+
19 22
     class Choice(meta.Model):
20 23
         poll = meta.ForeignKey(Poll, edit_inline=meta.TABULAR,
21 24
             num_in_admin=10, min_num_in_admin=5)
22 25
         choice = meta.CharField(maxlength=255, core=True)
23 26
         votes = meta.IntegerField(editable=False, default=0)
24 27
 
  28
+        def __repr__(self):
  29
+            return self.choice
  30
+
25 31
 Basic lookup functions
26 32
 ======================
27 33
 
28  
-Each model exposes three basic functions for lookups: ``get_object``,
29  
-``get_list``, and ``get_count``.  These functions all take the same arguments,
30  
-but ``get_object`` assumes that only a single record will be returned (and
31  
-raises ``AssertionError`` if that's not true), ``get_count`` simply returns a
32  
-count of objects matched by the lookup, and ``get_list`` returns a list of objects.
  34
+Each model exposes these module-level functions for lookups:
  35
+
  36
+get_object(**kwargs)
  37
+--------------------
  38
+
  39
+Returns the object matching the given lookup parameters, which should be in
  40
+the format described in "Field lookups" below. Raises a module-level
  41
+``*DoesNotExist`` exception if an object wasn't found for the given parameters.
  42
+Raises ``AssertionError`` if more than one object was found.
  43
+
  44
+get_list(**kwargs)
  45
+------------------
  46
+
  47
+Returns a list of objects matching the given lookup parameters, which should be
  48
+in 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.
  50
+
  51
+get_iterator(**kwargs)
  52
+----------------------
  53
+
  54
+Just like ``get_list()``, except it returns an iterator instead of a list. This
  55
+is more efficient for large result sets. This example shows the difference::
  56
+
  57
+    # get_list() loads all objects into memory.
  58
+    for obj in foos.get_list():
  59
+        print repr(obj)
  60
+
  61
+    # get_iterator() only loads a number of objects into memory at a time.
  62
+    for obj in foos.get_iterator():
  63
+        print repr(obj)
  64
+
  65
+get_count(**kwargs)
  66
+-------------------
  67
+
  68
+Returns an integer representing the number of objects in the database matching
  69
+the given lookup parameters, which should be in the format described in
  70
+"Field lookups" below. ``get_count()`` never raises exceptions
  71
+
  72
+Depending on which database you're using (e.g. PostgreSQL vs. MySQL), this may
  73
+return a long integer instead of a normal Python integer.
  74
+
  75
+get_values(**kwargs)
  76
+--------------------
  77
+
  78
+Just like ``get_list()``, except it returns a list of dictionaries instead of
  79
+model-instance objects.
  80
+
  81
+It accepts an optional parameter, ``fields``, which should be a list or tuple
  82
+of field names. If you don't specify ``fields``, each dictionary in the list
  83
+returned by ``get_values()`` will have a key and value for each field in the
  84
+database table. If you specify ``fields``, each dictionary will have only the
  85
+field keys/values for the fields you specify. Here's an example, using the
  86
+``Poll`` model defined above::
  87
+
  88
+    >>> from datetime import datetime
  89
+    >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
  90
+    ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
  91
+    >>> p1.save()
  92
+    >>> p2 = polls.Poll(slug='name', question="What's your name?",
  93
+    ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
  94
+    >>> p2.save()
  95
+    >>> polls.get_list()
  96
+    [What's up?, What's your name?]
  97
+    >>> polls.get_values()
  98
+    [{'id': 1, 'slug': 'whatsup', 'question': "What's up?", 'pub_date': datetime.datetime(2005, 2, 20), 'expire_date': datetime.datetime(2005, 3, 20)},
  99
+     {'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'])
  101
+    [{'id': 1, 'slug': 'whatsup'}, {'id': 2, 'slug': 'name'}]
  102
+
  103
+Use ``get_values()`` when you know you're only going to need a couple of field
  104
+values and you won't need the functionality of a model instance object. It's
  105
+more efficient to select only the fields you need to use.
  106
+
  107
+get_values_iterator(**kwargs)
  108
+-----------------------------
  109
+
  110
+Just like ``get_values()``, except it returns an iterator instead of a list.
  111
+See the section on ``get_iterator()`` above.
  112
+
  113
+get_in_bulk(id_list, **kwargs)
  114
+------------------------------
  115
+
  116
+Takes a list of IDs and returns a dictionary mapping each ID to an instance of
  117
+the object with the given ID. Also takes optional keyword lookup arguments,
  118
+which should be in the format described in "Field lookups" below. Here's an
  119
+example, using the ``Poll`` model defined above::
  120
+
  121
+    >>> from datetime import datetime
  122
+    >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
  123
+    ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
  124
+    >>> p1.save()
  125
+    >>> p2 = polls.Poll(slug='name', question="What's your name?",
  126
+    ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
  127
+    >>> p2.save()
  128
+    >>> polls.get_list()
  129
+    [What's up?, What's your name?]
  130
+    >>> polls.get_in_bulk([1])
  131
+    {1: What's up?}
  132
+    >>> polls.get_in_bulk([1, 2])
  133
+    {1: What's up?, 2: What's your name?}
33 134
 
34 135
 Field lookups
35 136
 =============
@@ -115,6 +216,8 @@ statements are equivalent::
115 216
     choices.get_list(poll__id__exact=3)
116 217
     choices.get_list(poll__pk=3)
117 218
 
  219
+If you pass an invalid keyword argument, the function will raise ``TypeError``.
  220
+
118 221
 .. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000
119 222
 
120 223
 Ordering
@@ -337,7 +440,7 @@ of objects then calling save() on them::
337 440
 Calling ``save()`` on an object with an id if ``None`` signifies to
338 441
 Django that the object is new and should be inserted.
339 442
 
340  
-Related objects (i.e. ``Choices``) are created using convience functions::
  443
+Related objects (e.g. ``Choices``) are created using convenience functions::
341 444
 
342 445
     >>> p.add_choice(choice="Over easy", votes=0)
343 446
     >>> p.add_choice(choice="Scrambled", votes=0)
@@ -346,12 +449,10 @@ Related objects (i.e. ``Choices``) are created using convience functions::
346 449
     >>> p.get_choice_count()
347 450
     4
348 451
 
349  
-Each of those ``add_choice`` methods is equivilent to (except obviously much
  452
+Each of those ``add_choice`` methods is equivalent to (except obviously much
350 453
 simpler than)::
351 454
 
352  
-    >>> c = polls.Choice(poll_id=p.id,
353  
-    ...                  choice="Over easy",
354  
-    ...                  votes=0)
  455
+    >>> c = polls.Choice(poll_id=p.id, choice="Over easy", votes=0)
355 456
     >>> c.save()
356 457
 
357 458
 Note that when using the `add_foo()`` methods, you do not give any value
@@ -361,4 +462,132 @@ the relation (``poll_id`` in this case).
361 462
 Deleting objects
362 463
 ================
363 464
 
364  
-The delete method, conveniently, is named ``delete()``.
  465
+The delete method, conveniently, is named ``delete()``. This method immediately
  466
+deletes the object and has no return value. Example::
  467
+
  468
+    >>> c.delete()
  469
+
  470
+Extra instance methods
  471
+======================
  472
+
  473
+In addition to ``save()``, ``delete()`` and all of the ``add_*`` and ``get_*``
  474
+related-object methods, a model object might get any or all of the following
  475
+methods:
  476
+
  477
+get_FOO_display()
  478
+-----------------
  479
+
  480
+For every field that has ``choices`` set, the object will have a
  481
+``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
  482
+method returns the "human-readable" value of the field. For example, in the
  483
+following model::
  484
+
  485
+    GENDER_CHOICES = (
  486
+        ('M', 'Male'),
  487
+        ('F', 'Female'),
  488
+    )
  489
+    class Person
  490
+        name = meta.CharField(maxlength=20)
  491
+        gender = meta.CharField(maxlength=1, choices=GENDER_CHOICES)
  492
+
  493
+...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
  494
+
  495
+    >>> p = Person(name='John', gender='M')
  496
+    >>> p.save()
  497
+    >>> p.gender
  498
+    'M'
  499
+    >>> p.get_gender_display()
  500
+    'Male'
  501
+
  502
+get_next_by_FOO(**kwargs) and get_previous_by_FOO(**kwargs)
  503
+-----------------------------------------------------------
  504
+
  505
+For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
  506
+the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
  507
+methods, where ``FOO`` is the name of the field. This returns the next and
  508
+previous object with respect to the date field, raising the appropriate
  509
+``*DoesNotExist`` exception when appropriate.
  510
+
  511
+Both methods accept optional keyword arguments, which should be in the format
  512
+described in "Field lookups" above.
  513
+
  514
+get_FOO_filename()
  515
+------------------
  516
+
  517
+For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
  518
+where ``FOO`` is the name of the field. This returns the full filesystem path
  519
+to the file, according to your ``MEDIA_ROOT`` setting.
  520
+
  521
+Note that ``ImageField`` is technically a subclass of ``FileField``, so every
  522
+model with an ``ImageField`` will also get this method.
  523
+
  524
+get_FOO_url()
  525
+-------------
  526
+
  527
+For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
  528
+where ``FOO`` is the name of the field. This returns the full URL to the file,
  529
+according to your ``MEDIA_URL`` setting. If the value is blank, this method
  530
+returns an empty string.
  531
+
  532
+get_FOO_size()
  533
+--------------
  534
+
  535
+For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
  536
+where ``FOO`` is the name of the field. This returns the size of the file, in
  537
+bytes. (Behind the scenes, it uses ``os.path.getsize``.)
  538
+
  539
+save_FOO_file(filename, raw_contents)
  540
+-------------------------------------
  541
+
  542
+For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
  543
+where ``FOO`` is the name of the field. This saves the given file to the
  544
+filesystem, using the given filename. If a file with the given filename already
  545
+exists, Django adds an underscore to the end of the filename (but before the
  546
+extension) until the filename is available.
  547
+
  548
+get_FOO_height() and get_FOO_width()
  549
+------------------------------------
  550
+
  551
+For every ``ImageField``, the object will have ``get_FOO_height()`` and
  552
+``get_FOO_width()`` methods, where ``FOO`` is the name of the field. This
  553
+returns the height (or width) of the image, as an integer, in pixels.
  554
+
  555
+Extra module functions
  556
+======================
  557
+
  558
+In addition to every function described in "Basic lookup functions" above, a
  559
+model module might get any or all of the following methods:
  560
+
  561
+get_FOO_list(kind, **kwargs)
  562
+----------------------------
  563
+
  564
+For every ``DateField`` and ``DateTimeField``, the model module will have a
  565
+``get_FOO_list()`` function, where ``FOO`` is the name of the field. This
  566
+returns a list of ``datetime.datetime`` objects representing all available
  567
+dates of the given scope, as defined by the ``kind`` argument. ``kind`` should
  568
+be either ``"year"``, ``"month"`` or ``"day"``. Each ``datetime.datetime``
  569
+object in the result list is "truncated" to the given ``type``.
  570
+
  571
+    * ``"year"`` returns a list of all distinct year values for the field.
  572
+    * ``"month"`` returns a list of all distinct year/month values for the field.
  573
+    * ``"day"`` returns a list of all distinct year/month/day values for the field.
  574
+
  575
+Here's an example, using the ``Poll`` model defined above::
  576
+
  577
+    >>> from datetime import datetime
  578
+    >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
  579
+    ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
  580
+    >>> p1.save()
  581
+    >>> p2 = polls.Poll(slug='name', question="What's your name?",
  582
+    ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
  583
+    >>> p2.save()
  584
+    >>> polls.get_pub_date_list('year')
  585
+    [datetime.datetime(2005, 1, 1)]
  586
+    >>> polls.get_pub_date_list('month')
  587
+    [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
  588
+    >>> polls.get_pub_date_list('day')
  589
+    [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
  590
+
  591
+``get_FOO_list()`` also accepts an optional keyword argument ``order``, which
  592
+should be either ``"ASC"`` or ``"DESC"``. This specifies how to order the
  593
+results. Default is ``"ASC"``.

0 notes on commit c2e42e1

Please sign in to comment.
Something went wrong with that request. Please try again.