Django

Code

root/django/branches/0.90-bugfixes/docs/db-api.txt

Revision 1155, 23.0 kB (checked in by adrian, 3 years ago)

Fixed #724 -- Ensured get_next_by_FOO() and get_previous_by_FOO() methods don't skip or duplicate any records in the case of duplicate values. Thanks for reporting the bug, mattycakes@gmail.com

Line 
1 ======================
2 Database API reference
3 ======================
4
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
9 .. _`data models`: http://www.djangoproject.com/documentation/model_api/
10
11 Throughout this reference, we'll refer to the following Poll application::
12
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()
18
19         def __repr__(self):
20             return self.question
21
22     class Choice(meta.Model):
23         poll = meta.ForeignKey(Poll, edit_inline=meta.TABULAR,
24             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)
27
28         def __repr__(self):
29             return self.choice
30
31 Basic lookup functions
32 ======================
33
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?}
134
135 Field lookups
136 =============
137
138 Basic field lookups take the form ``field__lookuptype`` (that's a
139 double-underscore). For example::
140
141     polls.get_list(pub_date__lte=datetime.datetime.now())
142
143 translates (roughly) into the following SQL::
144
145     SELECT * FROM polls_polls WHERE pub_date < NOW();
146
147 .. admonition:: How this is possible
148
149    Python has the ability to define functions that accept arbitrary name-value
150    arguments whose names and values are evaluated at run time. For more
151    information, see `Keyword Arguments`_ in the official Python tutorial.
152
153 The DB API supports the following lookup types:
154
155     ===========  ==============================================================
156     Type         Description
157     ===========  ==============================================================
158     exact        Exact match: ``polls.get_object(id__exact=14)``.
159     iexact       Case-insensitive exact match:
160                  ``polls.get_list(slug__iexact="foo")`` matches a slug of
161                  ``foo``, ``FOO``, ``fOo``, etc.
162     contains     Case-sensitive containment test:
163                  ``polls.get_list(question__contains="spam")`` returns all polls
164                  that contain "spam" in the question. (PostgreSQL and MySQL
165                  only. SQLite doesn't support case-sensitive LIKE statements;
166                  ``contains`` will act like ``icontains`` for SQLite.)
167     icontains    Case-insensitive containment test.
168     gt           Greater than: ``polls.get_list(id__gt=4)``.
169     gte          Greater than or equal to.
170     lt           Less than.
171     lte          Less than or equal to.
172     ne           Not equal to.
173     in           In a given list: ``polls.get_list(id__in=[1, 3, 4])`` returns
174                  a list of polls whose IDs are either 1, 3 or 4.
175     startswith   Case-sensitive starts-with:
176                  ``polls.get_list(question_startswith="Would")``. (PostgreSQL
177                  and MySQL only. SQLite doesn't support case-sensitive LIKE
178                  statements; ``startswith`` will act like ``istartswith`` for
179                  SQLite.)
180     endswith     Case-sensitive ends-with. (PostgreSQL and MySQL only.)
181     istartswith  Case-insensitive starts-with.
182     iendswith    Case-insensitive ends-with.
183     range        Range test:
184                  ``polls.get_list(pub_date__range=(start_date, end_date))``
185                  returns all polls with a pub_date between ``start_date``
186                  and ``end_date`` (inclusive).
187     year         For date/datetime fields, exact year match:
188                  ``polls.get_count(pub_date__year=2005)``.
189     month        For date/datetime fields, exact month match.
190     day          For date/datetime fields, exact day match.
191     isnull       True/False; does is IF NULL/IF NOT NULL lookup:
192                  ``polls.get_list(expire_date__isnull=True)``.
193     ===========  ==============================================================
194
195 Multiple lookups are allowed, of course, and are translated as "AND"s::
196
197     polls.get_list(
198         pub_date__year=2005,
199         pub_date__month=1,
200         question__startswith="Would",
201     )
202
203 ...retrieves all polls published in January 2005 that have a question starting with "Would."
204
205 For convenience, there's a ``pk`` lookup type, which translates into
206 ``(primary_key)__exact``. In the polls example, these two statements are
207 equivalent::
208
209     polls.get_object(id__exact=3)
210     polls.get_object(pk=3)
211
212 ``pk`` lookups also work across joins. In the polls example, these two
213 statements are equivalent::
214
215     choices.get_list(poll__id__exact=3)
216     choices.get_list(poll__pk=3)
217
218 If you pass an invalid keyword argument, the function will raise ``TypeError``.
219
220 .. _`Keyword Arguments`: http://docs.python.org/tut/node6.html#SECTION006720000000000000000
221
222 Ordering
223 ========
224
225 The results are automatically ordered by the ordering tuple given by the
226 ``ordering`` key in the model, but the ordering may be explicitly
227 provided by the ``order_by`` argument to a lookup::
228
229     polls.get_list(
230         pub_date__year=2005,
231         pub_date__month=1,
232         order_by=('-pub_date', 'question'),
233     )
234
235 The result set above will be ordered by ``pub_date`` descending, then
236 by ``question`` ascending. The negative sign in front of "-pub_date" indicates
237 descending order. Ascending order is implied. To order randomly, use "?", like
238 so::
239
240     polls.get_list(order_by=['?'])
241
242 There's no way to specify whether ordering should be case sensitive. With
243 respect to case-sensitivity, Django will order results however your database
244 backend normally orders them.
245
246 Relationships (joins)
247 =====================
248
249 Joins may implicitly be performed by following relationships:
250 ``choices.get_list(poll__slug__exact="eggs")`` fetches a list of ``Choice``
251 objects where the associated ``Poll`` has a slug of ``eggs``.  Multiple levels
252 of joins are allowed.
253
254 Given an instance of an object, related objects can be looked-up directly using
255 convenience functions. For example, if ``p`` is a ``Poll`` instance,
256 ``p.get_choice_list()`` will return a list of all associated choices. Astute
257 readers will note that this is the same as
258 ``choices.get_list(poll_id__exact=p.id)``, except clearer.
259
260 Each type of relationship creates a set of methods on each object in the
261 relationship. These methods are created in both directions, so objects that are
262 "related-to" need not explicitly define reverse relationships; that happens
263 automatically.
264
265 One-to-one relations
266 --------------------
267
268 Each object in a one-to-one relationship will have a ``get_relatedobjectname()``
269 method. For example::
270
271     class Place(meta.Model):
272         # ...
273
274     class Restaurant(meta.Model):
275         # ...
276         the_place = meta.OneToOneField(places.Place)
277
278 In the above example, each ``Place`` will have a ``get_restaurant()`` method,
279 and each ``Restaurant`` will have a ``get_theplace()`` method.
280
281 Many-to-one relations
282 ---------------------
283
284 In each many-to-one relationship, the related object will have a
285 ``get_relatedobject()`` method, and the related-to object will have
286 ``get_relatedobject()``, ``get_relatedobject_list()``, and
287 ``get_relatedobject_count()`` methods (the same as the module-level
288 ``get_object()``, ``get_list()``, and ``get_count()`` methods).
289
290 In the poll example above, here are the available choice methods on a ``Poll`` object ``p``::
291
292     p.get_choice()
293     p.get_choice_list()
294     p.get_choice_count()
295
296 And a ``Choice`` object ``c`` has the following method::
297
298     c.get_poll()
299
300 Many-to-many relations
301 ----------------------
302
303 Many-to-many relations result in the same set of methods as `Many-to-one relations`_,
304 except that the ``get_relatedobject_list()`` function on the related object will
305 return a list of instances instead of a single instance.  So, if the relationship
306 between ``Poll`` and ``Choice`` was many-to-many, ``choice.get_poll_list()`` would
307 return a list.
308
309 Relationships across applications
310 ---------------------------------
311
312 If a relation spans applications -- if ``Place`` was had a ManyToOne relation to
313 a ``geo.City`` object, for example -- the name of the other application will be
314 added to the method, i.e. ``place.get_geo_city()`` and
315 ``city.get_places_place_list()``.
316
317 Selecting related objects
318 -------------------------
319
320 Relations are the bread and butter of databases, so there's an option to "follow"
321 all relationships and pre-fill them in a simple cache so that later calls to
322 objects with a one-to-many relationship don't have to hit the database. Do this by
323 passing ``select_related=True`` to a lookup. This results in (sometimes much) larger
324 queries, but it means that later use of relationships is much faster.
325
326 For example, using the Poll and Choice models from above, if you do the following::
327
328     c = choices.get_object(id__exact=5, select_related=True)
329
330 Then subsequent calls to ``c.get_poll()`` won't hit the database.
331
332 Note that ``select_related`` follows foreign keys as far as possible. If you have the
333 following models::
334
335     class Poll(meta.Model):
336         # ...
337
338     class Choice(meta.Model):
339         # ...
340         poll = meta.ForeignKey(Poll)
341
342     class SingleVote(meta.Model):
343         # ...
344         choice = meta.ForeignKey(Choice)
345
346 then a call to ``singlevotes.get_object(id__exact=4, select_related=True)`` will
347 cache the related choice *and* the related poll::
348
349     >>> sv = singlevotes.get_object(id__exact=4, select_related=True)
350     >>> c = sv.get_choice()        # Doesn't hit the database.
351     >>> p = c.get_poll()           # Doesn't hit the database.
352
353     >>> sv = singlevotes.get_object(id__exact=4) # Note no "select_related".
354     >>> c = sv.get_choice()        # Hits the database.
355     >>> p = c.get_poll()           # Hits the database.
356
357 Limiting selected rows
358 ======================
359
360 The ``limit``, ``offset``, and ``distinct`` keywords can be used to control
361 which rows are returned.  Both ``limit`` and ``offset`` should be integers which
362 will be directly passed to the SQL ``LIMIT``/``OFFSET`` commands.
363
364 If ``distinct`` is True, only distinct rows will be returned. This is equivalent
365 to a ``SELECT DISTINCT`` SQL clause.
366
367 Other lookup options
368 ====================
369
370 There are a few other ways of more directly controlling the generated SQL
371 for the lookup.  Note that by definition these extra lookups may not be
372 portable to different database engines (because you're explicitly writing
373 SQL code) and should be avoided if possible.:
374
375 ``params``
376 ----------
377
378 All the extra-SQL params described below may use standard Python string
379 formatting codes to indicate parameters that the database engine will
380 automatically quote.  The ``params`` argument can contain any extra
381 parameters to be substituted.
382
383 ``select``
384 ----------
385
386 The ``select`` keyword allows you to select extra fields.  This should be a
387 dictionary mapping attribute names to a SQL clause to use to calculate that
388 attribute. For example::
389
390     polls.get_list(
391         select={
392             'choice_count': 'SELECT COUNT(*) FROM choices WHERE poll_id = polls.id'
393         }
394     )
395
396 Each of the resulting ``Poll`` objects will have an extra attribute, ``choice_count``,
397 an integer count of associated ``Choice`` objects. Note that the parenthesis required by
398 most database engines around sub-selects are not required in Django's ``select``
399 clauses.
400
401 ``where`` / ``tables``
402 ----------------------
403
404 If you need to explicitly pass extra ``WHERE`` clauses -- perhaps to perform
405 non-explicit joins -- use the ``where`` keyword. If you need to
406 join other tables into your query, you can pass their names to ``tables``.
407
408 ``where`` and ``tables`` both take a list of strings. All ``where`` parameters
409 are "AND"ed to any other search criteria.
410
411 For example::
412
413     polls.get_list(question__startswith='Who', where=['id IN (3, 4, 5, 20)'])
414
415 ...translates (roughly) into the following SQL:
416
417     SELECT * FROM polls_polls WHERE question LIKE 'Who%' AND id IN (3, 4, 5, 20);
418
419 Changing objects
420 ================
421
422 Once you've retrieved an object from the database using any of the above
423 options, changing it is extremely easy.  Make changes directly to the
424 objects fields, then call the object's ``save()`` method::
425
426     >>> p = polls.get_object(id__exact=15)
427     >>> p.slug = "new_slug"
428     >>> p.pub_date = datetime.datetime.now()
429     >>> p.save()
430
431 Creating new objects
432 ====================
433
434 Creating new objects (i.e. ``INSERT``) is done by creating new instances
435 of objects then calling save() on them::
436
437     >>> p = polls.Poll(slug="eggs",
438     ...                question="How do you like your eggs?",
439     ...                pub_date=datetime.datetime.now(),
440     ...                expire_date=some_future_date)
441     >>> p.save()
442
443 Calling ``save()`` on an object with a primary key whose value is ``None``
444 signifies to Django that the object is new and should be inserted.
445
446 Related objects (e.g. ``Choices``) are created using convenience functions::
447
448     >>> p.add_choice(choice="Over easy", votes=0)
449     >>> p.add_choice(choice="Scrambled", votes=0)
450     >>> p.add_choice(choice="Fertilized", votes=0)
451     >>> p.add_choice(choice="Poached", votes=0)
452     >>> p.get_choice_count()
453     4
454
455 Each of those ``add_choice`` methods is equivalent to (but much simpler than)::
456
457     >>> c = polls.Choice(poll_id=p.id, choice="Over easy", votes=0)
458     >>> c.save()
459
460 Note that when using the `add_foo()`` methods, you do not give any value
461 for the ``id`` field, nor do you give a value for the field that stores
462 the relation (``poll_id`` in this case).
463
464 The ``add_FOO()`` method always returns the newly created object.
465
466 Deleting objects
467 ================
468
469 The delete method, conveniently, is named ``delete()``. This method immediately
470 deletes the object and has no return value. Example::
471
472     >>> c.delete()
473
474 Extra instance methods
475 ======================
476
477 In addition to ``save()``, ``delete()`` and all of the ``add_*`` and ``get_*``
478 related-object methods, a model object might get any or all of the following
479 methods:
480
481 get_FOO_display()
482 -----------------
483
484 For every field that has ``choices`` set, the object will have a
485 ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
486 method returns the "human-readable" value of the field. For example, in the
487 following model::
488
489     GENDER_CHOICES = (
490         ('M', 'Male'),
491         ('F', 'Female'),
492     )
493     class Person
494         name = meta.CharField(maxlength=20)
495         gender = meta.CharField(maxlength=1, choices=GENDER_CHOICES)
496
497 ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
498
499     >>> p = Person(name='John', gender='M')
500     >>> p.save()
501     >>> p.gender
502     'M'
503     >>> p.get_gender_display()
504     'Male'
505
506 get_next_by_FOO(\**kwargs) and get_previous_by_FOO(\**kwargs)
507 -------------------------------------------------------------
508
509 For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
510 the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
511 methods, where ``FOO`` is the name of the field. This returns the next and
512 previous object with respect to the date field, raising the appropriate
513 ``*DoesNotExist`` exception when appropriate.
514
515 Both methods accept optional keyword arguments, which should be in the format
516 described in "Field lookups" above.
517
518 Note that in the case of identical date values, these methods will use the ID
519 as a fallback check. This guarantees that no records are skipped or duplicated.
520 For a full example, see the `lookup API sample model_`.
521
522 .. _lookup API sample model: http://www.djangoproject.com/documentation/models/lookup/
523
524 get_FOO_filename()
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 filesystem path
529 to the file, according to your ``MEDIA_ROOT`` setting.
530
531 Note that ``ImageField`` is technically a subclass of ``FileField``, so every
532 model with an ``ImageField`` will also get this method.
533
534 get_FOO_url()
535 -------------
536
537 For every ``FileField``, the object will have a ``get_FOO_url()`` method,
538 where ``FOO`` is the name of the field. This returns the full URL to the file,
539 according to your ``MEDIA_URL`` setting. If the value is blank, this method
540 returns an empty string.
541
542 get_FOO_size()
543 --------------
544
545 For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
546 where ``FOO`` is the name of the field. This returns the size of the file, in
547 bytes. (Behind the scenes, it uses ``os.path.getsize``.)
548
549 save_FOO_file(filename, raw_contents)
550 -------------------------------------
551
552 For every ``FileField``, the object will have a ``get_FOO_filename()`` method,
553 where ``FOO`` is the name of the field. This saves the given file to the
554 filesystem, using the given filename. If a file with the given filename already
555 exists, Django adds an underscore to the end of the filename (but before the
556 extension) until the filename is available.
557
558 get_FOO_height() and get_FOO_width()
559 ------------------------------------
560
561 For every ``ImageField``, the object will have ``get_FOO_height()`` and
562 ``get_FOO_width()`` methods, where ``FOO`` is the name of the field. This
563 returns the height (or width) of the image, as an integer, in pixels.
564
565 Extra module functions
566 ======================
567
568 In addition to every function described in "Basic lookup functions" above, a
569 model module might get any or all of the following methods:
570
571 get_FOO_list(kind, \**kwargs)
572 -----------------------------
573
574 For every ``DateField`` and ``DateTimeField``, the model module will have a
575 ``get_FOO_list()`` function, where ``FOO`` is the name of the field. This
576 returns a list of ``datetime.datetime`` objects representing all available
577 dates of the given scope, as defined by the ``kind`` argument. ``kind`` should
578 be either ``"year"``, ``"month"`` or ``"day"``. Each ``datetime.datetime``
579 object in the result list is "truncated" to the given ``type``.
580
581     * ``"year"`` returns a list of all distinct year values for the field.
582     * ``"month"`` returns a list of all distinct year/month values for the field.
583     * ``"day"`` returns a list of all distinct year/month/day values for the field.
584
585 Additional, optional keyword arguments, in the format described in
586 "Field lookups" above, are also accepted.
587
588 Here's an example, using the ``Poll`` model defined above::
589
590     >>> from datetime import datetime
591     >>> p1 = polls.Poll(slug='whatsup', question="What's up?",
592     ...     pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20))
593     >>> p1.save()
594     >>> p2 = polls.Poll(slug='name', question="What's your name?",
595     ...     pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20))
596     >>> p2.save()
597     >>> polls.get_pub_date_list('year')
598     [datetime.datetime(2005, 1, 1)]
599     >>> polls.get_pub_date_list('month')
600     [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
601     >>> polls.get_pub_date_list('day')
602     [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
603     >>> polls.get_pub_date_list('day', question__contains='name')
604     [datetime.datetime(2005, 3, 20)]
605
606 ``get_FOO_list()`` also accepts an optional keyword argument ``order``, which
607 should be either ``"ASC"`` or ``"DESC"``. This specifies how to order the
608 results. Default is ``"ASC"``.
Note: See TracBrowser for help on using the browser.