Ticket #1464: db-api.patch
File db-api.patch, 17.1 KB (added by , 19 years ago) |
---|
-
docs/db-api.txt
10 10 11 11 Throughout this reference, we'll refer to the following Poll application:: 12 12 13 class Poll(m eta.Model):14 slug = m eta.SlugField(unique_for_month='pub_date')15 question = m eta.CharField(maxlength=255)16 pub_date = m eta.DateTimeField()17 expire_date = m eta.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() 18 18 19 19 def __repr__(self): 20 20 return self.question 21 21 22 class Choice(m eta.Model):23 poll = m eta.ForeignKey(Poll, edit_inline=meta.TABULAR,22 class Choice(models.Model): 23 poll = models.ForeignKey(Poll, edit_inline=meta.TABULAR, 24 24 num_in_admin=10, min_num_in_admin=5) 25 choice = m eta.CharField(maxlength=255, core=True)26 votes = m eta.IntegerField(editable=False, default=0)25 choice = models.CharField(maxlength=255, core=True) 26 votes = models.IntegerField(editable=False, default=0) 27 27 28 28 def __repr__(self): 29 29 return self.choice … … 33 33 34 34 Each model exposes these module-level functions for lookups: 35 35 36 get _object(\**kwargs)36 get(\**kwargs) 37 37 --------------------- 38 38 39 39 Returns the object matching the given lookup parameters, which should be in … … 41 41 ``*DoesNotExist`` exception if an object wasn't found for the given parameters. 42 42 Raises ``AssertionError`` if more than one object was found. 43 43 44 get_list(\**kwargs)44 filter(\**kwargs) 45 45 ------------------- 46 46 47 47 Returns a list of objects matching the given lookup parameters, which should be 48 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.49 parameters, it returns an empty list. ``filter()`` will always return a list. 50 50 51 51 get_iterator(\**kwargs) 52 52 ----------------------- 53 53 54 Just like `` get_list()``, except it returns an iterator instead of a list. This54 Just like ``filter()``, except it returns an iterator instead of a list. This 55 55 is more efficient for large result sets. This example shows the difference:: 56 56 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(): 59 59 print repr(obj) 60 60 61 61 # get_iterator() only loads a number of objects into memory at a time. … … 75 75 get_values(\**kwargs) 76 76 --------------------- 77 77 78 Just like `` get_list()``, except it returns a list of dictionaries instead of78 Just like ``filter()``, except it returns a list of dictionaries instead of 79 79 model-instance objects. 80 80 81 81 It accepts an optional parameter, ``fields``, which should be a list or tuple … … 86 86 ``Poll`` model defined above:: 87 87 88 88 >>> from datetime import datetime 89 >>> p1 = polls.Poll(slug='whatsup', question="What's up?",89 >>> p1 = Poll(slug='whatsup', question="What's up?", 90 90 ... pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20)) 91 91 >>> p1.save() 92 >>> p2 = polls.Poll(slug='name', question="What's your name?",92 >>> p2 = Poll(slug='name', question="What's your name?", 93 93 ... pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20)) 94 94 >>> p2.save() 95 >>> polls.get_list()95 >>> Poll.objects.all() 96 96 [What's up?, What's your name?] 97 >>> polls.get_values()97 >>> Poll.objects.get_values() 98 98 [{'id': 1, 'slug': 'whatsup', 'question': "What's up?", 'pub_date': datetime.datetime(2005, 2, 20), 'expire_date': datetime.datetime(2005, 3, 20)}, 99 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'])100 >>> Poll.objects.get_values(fields=['id', 'slug']) 101 101 [{'id': 1, 'slug': 'whatsup'}, {'id': 2, 'slug': 'name'}] 102 102 103 103 Use ``get_values()`` when you know you're only going to need a couple of field … … 110 110 Just like ``get_values()``, except it returns an iterator instead of a list. 111 111 See the section on ``get_iterator()`` above. 112 112 113 get_in_bulk(id_list, \**kwargs)113 in_bulk(id_list, \**kwargs) 114 114 ------------------------------- 115 115 116 116 Takes a list of IDs and returns a dictionary mapping each ID to an instance of … … 119 119 example, using the ``Poll`` model defined above:: 120 120 121 121 >>> from datetime import datetime 122 >>> p1 = polls.Poll(slug='whatsup', question="What's up?",122 >>> p1 = Poll(slug='whatsup', question="What's up?", 123 123 ... pub_date=datetime(2005, 2, 20), expire_date=datetime(2005, 3, 20)) 124 124 >>> p1.save() 125 >>> p2 = polls.Poll(slug='name', question="What's your name?",125 >>> p2 = Poll(slug='name', question="What's your name?", 126 126 ... pub_date=datetime(2005, 3, 20), expire_date=datetime(2005, 4, 20)) 127 127 >>> p2.save() 128 >>> polls.get_list()128 >>> Poll.objects.all() 129 129 [What's up?, What's your name?] 130 >>> polls.get_in_bulk([1])130 >>> Poll.objects.in_bulk([1]) 131 131 {1: What's up?} 132 >>> polls.get_in_bulk([1, 2])132 >>> Poll.objects.in_bulk([1, 2]) 133 133 {1: What's up?, 2: What's your name?} 134 134 135 135 Field lookups … … 138 138 Basic field lookups take the form ``field__lookuptype`` (that's a 139 139 double-underscore). For example:: 140 140 141 polls.get_list(pub_date__lte=datetime.datetime.now())141 Poll.objects.filter(pub_date__lte=datetime.datetime.now()) 142 142 143 143 translates (roughly) into the following SQL:: 144 144 145 SELECT * FROM polls_poll sWHERE pub_date <= NOW();145 SELECT * FROM polls_poll WHERE pub_date <= NOW(); 146 146 147 147 .. admonition:: How this is possible 148 148 … … 155 155 =========== ============================================================== 156 156 Type Description 157 157 =========== ============================================================== 158 exact Exact match: `` polls.get_object(id__exact=14)``.158 exact Exact match: ``Poll.objects.get(id__exact=14)``. 159 159 iexact Case-insensitive exact match: 160 `` polls.get_list(slug__iexact="foo")`` matches a slug of160 ``Poll.objects.filter(slug__iexact="foo")`` matches a slug of 161 161 ``foo``, ``FOO``, ``fOo``, etc. 162 162 contains Case-sensitive containment test: 163 `` polls.get_list(question__contains="spam")`` returns all polls163 ``Poll.objects.filter(question__contains="spam")`` returns all polls 164 164 that contain "spam" in the question. (PostgreSQL and MySQL 165 165 only. SQLite doesn't support case-sensitive LIKE statements; 166 166 ``contains`` will act like ``icontains`` for SQLite.) 167 167 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)``. 169 169 gte Greater than or equal to. 170 170 lt Less than. 171 171 lte Less than or equal to. 172 172 ne Not equal to. 173 in In a given list: `` polls.get_list(id__in=[1, 3, 4])`` returns173 in In a given list: ``Poll.objects.filter(id__in=[1, 3, 4])`` returns 174 174 a list of polls whose IDs are either 1, 3 or 4. 175 175 startswith Case-sensitive starts-with: 176 `` polls.get_list(question__startswith="Would")``. (PostgreSQL176 ``Poll.objects.filter(question__startswith="Would")``. (PostgreSQL 177 177 and MySQL only. SQLite doesn't support case-sensitive LIKE 178 178 statements; ``startswith`` will act like ``istartswith`` for 179 179 SQLite.) … … 181 181 istartswith Case-insensitive starts-with. 182 182 iendswith Case-insensitive ends-with. 183 183 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))`` 185 185 returns all polls with a pub_date between ``start_date`` 186 186 and ``end_date`` (inclusive). 187 187 year For date/datetime fields, exact year match: 188 `` polls.get_count(pub_date__year=2005)``.188 ``Poll.objects.count(pub_date__year=2005)``. 189 189 month For date/datetime fields, exact month match. 190 190 day For date/datetime fields, exact day match. 191 191 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)``. 193 193 =========== ============================================================== 194 194 195 195 Multiple lookups are allowed, of course, and are translated as "AND"s:: 196 196 197 polls.get_list(197 Poll.objects.filter( 198 198 pub_date__year=2005, 199 199 pub_date__month=1, 200 200 question__startswith="Would", … … 203 203 ...retrieves all polls published in January 2005 that have a question starting with "Would." 204 204 205 205 For convenience, there's a ``pk`` lookup type, which translates into 206 ``(primary_key) __exact``. In the polls example, these two statements are206 ``(primary_key)``. In the polls example, these two statements are 207 207 equivalent:: 208 208 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) 211 211 212 212 ``pk`` lookups also work across joins. In the polls example, these two 213 213 statements are equivalent:: 214 214 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) 217 217 218 218 If you pass an invalid keyword argument, the function will raise ``TypeError``. 219 219 … … 228 228 229 229 A ``Q`` object is an instance of ``django.core.meta.Q``, used to encapsulate a collection of 230 230 keyword 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::231 the basic lookup functions like get() and filter(). For example:: 232 232 233 233 Q(question__startswith='What') 234 234 … … 247 247 ``Q`` object arguments are provided to a lookup function, they will be "AND"ed together. 248 248 For example:: 249 249 250 polls.get_object(250 Poll.objects.get( 251 251 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)) 253 253 ) 254 254 255 255 ... roughly translates into the SQL:: … … 262 262 However, if a ``Q`` object is provided, it must precede the definition of any keyword arguments. 263 263 For example:: 264 264 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)), 267 267 question__startswith='Who') 268 268 269 269 ... would be a valid query, equivalent to the previous example; but:: 270 270 271 271 # INVALID QUERY 272 polls.get_object(272 Poll.objects.get( 273 273 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))) 275 275 276 276 ... would not be valid. 277 277 278 278 A ``Q`` objects can also be provided to the ``complex`` keyword argument. For example:: 279 279 280 polls.get_object(280 Poll.objects.get( 281 281 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)) 284 284 ) 285 285 ) 286 286 … … 295 295 ``ordering`` key in the model, but the ordering may be explicitly 296 296 provided by the ``order_by`` argument to a lookup:: 297 297 298 polls.get_list(298 Poll.objects.filter( 299 299 pub_date__year=2005, 300 300 pub_date__month=1, 301 301 order_by=('-pub_date', 'question'), … … 306 306 descending order. Ascending order is implied. To order randomly, use "?", like 307 307 so:: 308 308 309 polls.get_list(order_by=['?'])309 Poll.objects.filter(order_by=['?']) 310 310 311 311 To order by a field in a different table, add the other table's name and a dot, 312 312 like so:: 313 313 314 choices.get_list(order_by=('polls.pub_date', 'choice'))314 Choice.objects.filter(order_by=('Poll.pub_date', 'choice')) 315 315 316 316 There's no way to specify whether ordering should be case sensitive. With 317 317 respect to case-sensitivity, Django will order results however your database … … 321 321 ===================== 322 322 323 323 Joins 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`` 325 325 objects where the associated ``Poll`` has a slug of ``eggs``. Multiple levels 326 326 of joins are allowed. 327 327 328 328 Given an instance of an object, related objects can be looked-up directly using 329 329 convenience functions. For example, if ``p`` is a ``Poll`` instance, 330 ``p. get_choice_list()`` will return a list of all associated choices. Astute330 ``p.choice_set.all()`` will return a list of all associated choices. Astute 331 331 readers 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. 333 333 334 334 Each type of relationship creates a set of methods on each object in the 335 335 relationship. These methods are created in both directions, so objects that are … … 342 342 Each object in a one-to-one relationship will have a ``get_relatedobjectname()`` 343 343 method. For example:: 344 344 345 class Place(m eta.Model):345 class Place(models.Model): 346 346 # ... 347 347 348 class Restaurant(m eta.Model):348 class Restaurant(models.Model): 349 349 # ... 350 the_place = m eta.OneToOneField(places.Place)350 the_place = models.OneToOneField(Place) 351 351 352 352 In the above example, each ``Place`` will have a ``get_restaurant()`` method, 353 353 and each ``Restaurant`` will have a ``get_the_place()`` method. … … 359 359 ``get_relatedobject()`` method, and the related-to object will have 360 360 ``get_relatedobject()``, ``get_relatedobject_list()``, and 361 361 ``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). 363 363 364 364 In the poll example above, here are the available choice methods on a ``Poll`` object ``p``:: 365 365 … … 399 399 400 400 For example, using the Poll and Choice models from above, if you do the following:: 401 401 402 c = choices.get_object(id__exact=5, select_related=True)402 c = Choice.objects.get(id=5, select_related=True) 403 403 404 404 Then subsequent calls to ``c.get_poll()`` won't hit the database. 405 405 406 406 Note that ``select_related`` follows foreign keys as far as possible. If you have the 407 407 following models:: 408 408 409 class Poll(m eta.Model):409 class Poll(models.Model): 410 410 # ... 411 411 412 class Choice(m eta.Model):412 class Choice(models.Model): 413 413 # ... 414 poll = m eta.ForeignKey(Poll)414 poll = models.ForeignKey(Poll) 415 415 416 416 class SingleVote(meta.Model): 417 417 # ... 418 choice = m eta.ForeignKey(Choice)418 choice = models.ForeignKey(Choice) 419 419 420 then a call to ``singlevotes.get_object(id __exact=4, select_related=True)`` will420 then a call to ``singlevotes.get_object(id=4, select_related=True)`` will 421 421 cache the related choice *and* the related poll:: 422 422 423 >>> sv = singlevotes.get_object(id __exact=4, select_related=True)423 >>> sv = singlevotes.get_object(id=4, select_related=True) 424 424 >>> c = sv.get_choice() # Doesn't hit the database. 425 425 >>> p = c.get_poll() # Doesn't hit the database. 426 426 427 >>> sv = singlevotes.get_object(id __exact=4) # Note no "select_related".427 >>> sv = singlevotes.get_object(id=4) # Note no "select_related". 428 428 >>> c = sv.get_choice() # Hits the database. 429 429 >>> p = c.get_poll() # Hits the database. 430 430 … … 465 465 dictionary mapping attribute names to a SQL clause to use to calculate that 466 466 attribute. For example:: 467 467 468 polls.get_list(468 Poll.objects.filter( 469 469 select={ 470 470 'choice_count': 'SELECT COUNT(*) FROM choices WHERE poll_id = polls.id' 471 471 } … … 488 488 489 489 For example:: 490 490 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)']) 492 492 493 493 ...translates (roughly) into the following SQL: 494 494 … … 512 512 Creating new objects (i.e. ``INSERT``) is done by creating new instances 513 513 of objects then calling save() on them:: 514 514 515 >>> p = polls.Poll(slug="eggs",515 >>> p = Poll(slug="eggs", 516 516 ... question="How do you like your eggs?", 517 517 ... pub_date=datetime.datetime.now(), 518 518 ... expire_date=some_future_date) … … 532 532 533 533 Each of those ``add_choice`` methods is equivalent to (but much simpler than):: 534 534 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) 536 536 >>> c.save() 537 537 538 538 Note that when using the `add_foo()`` methods, you do not give any value