| 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``. |
|---|
| | 49 | Querying in Django is based upon the construction and evaluation of Query |
|---|
| | 50 | Sets. |
|---|
| | 51 | |
|---|
| | 52 | A Query Set is a database-independent representation of a group of objects |
|---|
| | 53 | that all meet a given set of criteria. However, the determination of which |
|---|
| | 54 | objects are actually members of the Query Set is not made until you formally |
|---|
| | 55 | evaluate the Query Set. |
|---|
| | 56 | |
|---|
| | 57 | To construct a Query Set that meets your requirements, you start by obtaining |
|---|
| | 58 | an initial Query Set that describes all objects of a given type. This initial |
|---|
| | 59 | Query Set can then be refined using a range of operations. Once you have |
|---|
| | 60 | refined your Query Set to the point where it describes the group of objects |
|---|
| | 61 | you require, it can be evaluated (using iterators, slicing, or one of a range |
|---|
| | 62 | of other techniques), yielding an object or list of objects that meet the |
|---|
| | 63 | specifications of the Query Set. |
|---|
| | 64 | |
|---|
| | 65 | Obtaining an Initial Query Set |
|---|
| | 66 | ============================== |
|---|
| | 67 | |
|---|
| | 68 | Every 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 |
|---|
| | 70 | of initial Query Sets. The Manager acts as a Query Set that describes all |
|---|
| | 71 | objects of the type being managed; ``Polls.objects`` is the initial Query Set |
|---|
| | 72 | that contains all Polls in the database. |
|---|
| | 73 | |
|---|
| | 74 | The initial Query Set on the Manager behaves in the same way as every other |
|---|
| | 75 | Query Set in every respect except one - it cannot be evaluated. To overcome |
|---|
| | 76 | this limitation, the Manager Query Set has an ``all()`` method. The ``all()`` |
|---|
| | 77 | method produces a copy of the initial Query Set - a copy that *can* be |
|---|
| | 78 | evaluated:: |
|---|
| | 79 | |
|---|
| | 80 | all_polls = Poll.objects.all() |
|---|
| 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() |
|---|
| | 106 | The result of refining a Query Set is itself a Query Set; so it is possible to |
|---|
| | 107 | chain 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 |
|---|
| | 115 | another filter to remove elements present in the initial Query Set. The |
|---|
| | 116 | final result is a Query Set containing all Polls with a question that |
|---|
| | 117 | starts with "What", that were published between 1 Jan 2005 and today. |
|---|
| | 118 | |
|---|
| | 119 | Each Query Set is a unique object. The process of refinement is not one |
|---|
| | 120 | of adding a condition to the initial Query Set. Rather, each refinement |
|---|
| | 121 | creates a separate and distinct Query Set that can be stored, used. and |
|---|
| | 122 | reused. 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 | |
|---|
| | 128 | will construct 3 Query Sets; a base query set containing all Polls with a |
|---|
| | 129 | question that starts with "What", and two subsets of the base Query Set (one |
|---|
| | 130 | with an exlusion, one with a filter). The initial Query Set is unaffected by |
|---|
| | 131 | the refinement process. |
|---|
| | 132 | |
|---|
| | 133 | It should be noted that the construction of a Query Set does not involve any |
|---|
| | 134 | activity on the database. The database is not consulted until a Query Set is |
|---|
| | 135 | evaluated. |
|---|
| | 232 | OR lookups |
|---|
| | 233 | ========== |
|---|
| | 234 | |
|---|
| | 235 | Keyword argument queries are "AND"ed together. If you have more |
|---|
| | 236 | complex query requirements (for example, you need to include an ``OR`` |
|---|
| | 237 | statement in your query), you need to use ``Q`` objects. |
|---|
| | 238 | |
|---|
| | 239 | A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a |
|---|
| | 240 | collection of keyword arguments. These keyword arguments are specified in |
|---|
| | 241 | the same way as keyword arguments to the basic lookup functions like get() |
|---|
| | 242 | and filter(). For example:: |
|---|
| | 243 | |
|---|
| | 244 | Q(question__startswith='What') |
|---|
| | 245 | |
|---|
| | 246 | is a ``Q`` object encapsulating a single ``LIKE`` query. ``Q`` objects can be |
|---|
| | 247 | combined 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 | |
|---|
| | 257 | You can compose statements of arbitrary complexity by combining ``Q`` objects |
|---|
| | 258 | with the ``&`` and ``|`` operators. Parenthetical grouping can also be used. |
|---|
| | 259 | |
|---|
| | 260 | One or more ``Q`` objects can then provided as arguments to the lookup |
|---|
| | 261 | functions. If multiple ``Q`` object arguments are provided to a lookup |
|---|
| | 262 | function, 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 | |
|---|
| | 274 | If necessary, lookup functions can mix the use of ``Q`` objects and keyword |
|---|
| | 275 | arguments. All arguments provided to a lookup function (be they keyword |
|---|
| | 276 | argument or ``Q`` object) are "AND"ed together. However, if a ``Q`` object is |
|---|
| | 277 | provided, it must precede the definition of any keyword arguments. For |
|---|
| | 278 | example:: |
|---|
| | 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 | |
|---|
| | 293 | A ``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 | |
|---|
| | 302 | See the `OR lookups examples page`_ for more examples. |
|---|
| | 303 | |
|---|
| | 304 | .. _OR lookups examples page: http://www.djangoproject.com/documentation/models/or_lookups/ |
|---|
| | 305 | |
|---|
| 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 . :: |
|---|
| | 318 | will print all the Poll objects, using the ``__repr__()`` method of Poll. |
|---|
| | 319 | |
|---|
| | 320 | A 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 | |
|---|
| | 326 | Query Sets are lazy objects - that is, they are not *actually* sets (or |
|---|
| | 327 | lists) that contain all the objects that they represent. Python protocol |
|---|
| | 328 | magic is used to make the Query Set *look* like an iterable, sliceable |
|---|
| | 329 | object, but behind the scenes, Django is using caching to only instantiate |
|---|
| | 330 | objects as they are required. |
|---|
| | 331 | |
|---|
| | 332 | If you really need to have a list, you can force the evaluation of the |
|---|
| | 333 | lazy object:: |
|---|
| | 334 | |
|---|
| 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 | | -------------- |
|---|
| | 337 | However - be warned; this could have a large memory overhead, as Django will |
|---|
| | 338 | create an in-memory representation of every element of the list. |
|---|
| | 339 | |
|---|
| | 340 | Caching and Query Sets |
|---|
| | 341 | ====================== |
|---|
| | 342 | |
|---|
| | 343 | Each Query Set contains a cache. In a newly created Query Set, this cache |
|---|
| | 344 | is unpopulated. When a Query Set is evaluated for the first time, Django |
|---|
| | 345 | makes a database query to populate the cache, and then returns the results |
|---|
| | 346 | that have been explicitly requested (e.g., the next element if iteration |
|---|
| | 347 | is in use). Subsequent evaluations of the Query Set reuse the cached results. |
|---|
| | 348 | |
|---|
| | 349 | This caching behavior must be kept in mind when using Query Sets. For |
|---|
| | 350 | example, the following will cause two temporary Query Sets to be created, |
|---|
| | 351 | evaluated, 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 | |
|---|
| | 356 | On a small, low-traffic website, this may not pose a serious problem. However, |
|---|
| | 357 | on a high traffic website, it effectively doubles your database load. In |
|---|
| | 358 | addition, there is a possibility that the two lists may not be identical, |
|---|
| | 359 | since a poll may be added or deleted by another user between making the two |
|---|
| | 360 | requests. |
|---|
| | 361 | |
|---|
| | 362 | To 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 | |
|---|
| | 368 | Specialist Query Set Evaluation |
|---|
| | 369 | =============================== |
|---|
| | 370 | |
|---|
| | 371 | The following specialist functions can also be used to evaluate a Query Set. |
|---|
| | 372 | Unlike iteration or slicing, these methods do not populate the cache; each |
|---|
| | 373 | time one of these evaluation functions is used, the database will be queried. |
|---|
| | 374 | |
|---|
| | 375 | ``get(**kwargs)`` |
|---|
| | 376 | ----------------- |
|---|
| 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 | | |
|---|
| 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 |
|---|
| | 419 | When you define a relationship in a model (i.e., a ForeignKey, |
|---|
| | 420 | OneToOneField, or ManyToManyField), Django uses the name of the |
|---|
| | 421 | relationship to add a descriptor_ on every instance of the model. |
|---|
| | 422 | This descriptor behaves just like a normal attribute, providing |
|---|
| | 423 | access to the related object or objects. For example, |
|---|
| | 424 | ``mychoice.poll`` will return the poll object associated with a specific |
|---|
| | 425 | instance of ``Choice``. |
|---|
| | 426 | |
|---|
| | 427 | .. _descriptor: http://users.rcn.com/python/download/Descriptor.htm |
|---|
| | 428 | |
|---|
| | 429 | Django also adds a descriptor for the 'other' side of the relationship - |
|---|
| | 430 | the link from the related model to the model that defines the relationship. |
|---|
| | 431 | Since the related model has no explicit reference to the source model, |
|---|
| | 432 | Django will automatically derive a name for this descriptor. The name that |
|---|
| | 433 | Django chooses depends on the type of relation that is represented. However, |
|---|
| | 434 | if the definition of the relation has a `related_name` parameter, Django |
|---|
| | 435 | will use this name in preference to deriving a name. |
|---|
| | 436 | |
|---|
| | 437 | There are two types of descriptor that can be employed: Single Object |
|---|
| | 438 | Descriptors and Object Set Descriptors. The following table describes |
|---|
| | 439 | when each descriptor type is employed. The local model is the model on |
|---|
| | 440 | which the relation is defined; the related model is the model referred |
|---|
| | 441 | to 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 | |
|---|
| | 453 | Single Object Descriptor |
|---|
| | 454 | ------------------------ |
|---|
| | 455 | |
|---|
| | 456 | If the related object is a single object, the descriptor acts |
|---|
| | 457 | just 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 | |
|---|
| | 466 | Whenever a change is made to a Single Object Descriptor, save() |
|---|
| | 467 | must be called to commit the change to the database. |
|---|
| | 468 | |
|---|
| | 469 | If no `related_name` parameter is defined, Django will use the |
|---|
| | 470 | lower case version of the source model name as the name for the |
|---|
| | 471 | related descriptor. For example, if the ``Choice`` model had |
|---|
| | 472 | a 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 | |
|---|
| | 481 | By default, relations do not allow values of None; if you attempt |
|---|
| | 482 | to assign None to a Single Object Descriptor, an AttributeError |
|---|
| | 483 | will be thrown. However, if the relation has 'null=True' set |
|---|
| | 484 | (i.e., the database will allow NULLs for the relation), None can |
|---|
| | 485 | be assigned and returned by the descriptor to represent empty |
|---|
| | 486 | relations. |
|---|
| | 487 | |
|---|
| | 488 | Access to Single Object Descriptors is cached. The first time |
|---|
| | 489 | a descriptor on an instance is accessed, the database will be |
|---|
| | 490 | queried, and the result stored. Subsequent attempts to access |
|---|
| | 491 | the descriptor on the same instance will use the cached value. |
|---|
| | 492 | |
|---|
| | 493 | Object Set Descriptor |
|---|
| 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 | | ===================== |
|---|
| | 496 | An Object Set Descriptor acts just like the Manager - as an initial Query |
|---|
| | 497 | Set describing the set of objects related to an instance. As such, any |
|---|
| | 498 | query refining technique (filter, exclude, etc) can be used on the Object |
|---|
| | 499 | Set descriptor. This also means that Object Set Descriptor cannot be evaluated |
|---|
| | 500 | directly - the ``all()`` method must be used to produce a Query Set that |
|---|
| | 501 | can be evaluated. |
|---|
| | 502 | |
|---|
| | 503 | If no ``related_name`` parameter is defined, Django will use the lower case |
|---|
| | 504 | version of the source model name appended with `_set` as the name for the |
|---|
| | 505 | related descriptor. For example, every ``Poll`` object has a ``choice_set`` |
|---|
| | 506 | descriptor. |
|---|
| | 507 | |
|---|
| | 508 | The Object Set Descriptor has utility methods to add objects to the |
|---|
| | 509 | related 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 | |
|---|
| | 518 | The Object Set Descriptor may also have utility methods to remove objects |
|---|
| | 519 | from 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 | |
|---|
| | 527 | These 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 |
|---|
| | 529 | the related field cannot be set to None, then an object cannot be removed |
|---|
| | 530 | from one relation without adding it to another. |
|---|
| | 531 | |
|---|
| | 532 | The members of a related object set can be assigned from any iterable object. |
|---|
| | 533 | For example:: |
|---|
| | 534 | |
|---|
| | 535 | mypoll.choice_set = [choice1, choice2] |
|---|
| | 536 | |
|---|
| | 537 | If the ``clear()`` method is available, any pre-existing objects will be removed |
|---|
| | 538 | from the Object Set before all objects in the iterable (in this case, a list) |
|---|
| | 539 | are added to the choice set. If the ``clear()`` method is not available, all |
|---|
| | 540 | objects in the iterable will be added without removing any existing elements. |
|---|
| | 541 | |
|---|
| | 542 | Each of these operations on the Object Set Descriptor has immediate effect |
|---|
| | 543 | on the database - every add, create and remove is immediately and |
|---|
| | 544 | automatically saved to the database. |
|---|
| | 545 | |
|---|
| | 546 | Relationships and Queries |
|---|
| | 547 | ========================= |
|---|
| | 548 | |
|---|
| | 549 | When composing a ``filter`` or ``exclude`` refinement, it may be necessary to |
|---|
| | 550 | include conditions that span relationships. Relations can be followed as deep |
|---|
| | 551 | as required - just add descriptor names, separated by double underscores, to |
|---|
| | 552 | describe 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 |
|---|
| | 557 | has a name3 that has an attribute with lookup matching value'. In the Poll |
|---|
| | 558 | example:: |
|---|
| | 559 | |
|---|
| | 560 | Choice.objects.filter(poll__slug__startswith="eggs") |
|---|
| | 561 | |
|---|
| | 562 | ... describes the set of choices for which the related poll has a slug |
|---|
| | 563 | attribute that starts with "eggs". Django automatically composes the joins |
|---|
| | 564 | and conditions required for the SQL query. |
|---|
| | 565 | |
|---|
| | 566 | Specialist Query Sets Refinement |
|---|
| | 567 | ================================ |
|---|