| 1199 | | Since the related model has no explicit reference to the source model, |
|---|
| 1200 | | Django will automatically derive a name for this descriptor. The name that |
|---|
| 1201 | | Django chooses depends on the type of relation that is represented. However, |
|---|
| 1202 | | if the definition of the relation has a `related_name` parameter, Django |
|---|
| 1203 | | will use this name in preference to deriving a name. |
|---|
| 1204 | | |
|---|
| 1205 | | There are two types of descriptor that can be employed: Single Object |
|---|
| 1206 | | Descriptors and Object Set Descriptors. The following table describes |
|---|
| 1207 | | when each descriptor type is employed. The local model is the model on |
|---|
| 1208 | | which the relation is defined; the related model is the model referred |
|---|
| 1209 | | to by the relation. |
|---|
| 1210 | | |
|---|
| 1211 | | =============== ============= ============= |
|---|
| 1212 | | Relation Type Local Model Related Model |
|---|
| 1213 | | =============== ============= ============= |
|---|
| 1214 | | OneToOneField Single Object Single Object |
|---|
| 1215 | | |
|---|
| 1216 | | ForeignKey Single Object Object Set |
|---|
| 1217 | | |
|---|
| 1218 | | ManyToManyField Object Set Object Set |
|---|
| 1219 | | =============== ============= ============= |
|---|
| 1220 | | |
|---|
| 1221 | | Single object descriptor |
|---|
| | 1217 | For example, a ``Blog`` object ``b`` has access to a list of all related |
|---|
| | 1218 | ``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``. |
|---|
| | 1219 | |
|---|
| | 1220 | All examples in this section use the sample ``Blog``, ``Author`` and ``Entry`` |
|---|
| | 1221 | models defined at the top of this page. |
|---|
| | 1222 | |
|---|
| | 1223 | .. _descriptors: http://users.rcn.com/python/download/Descriptor.htm |
|---|
| | 1224 | |
|---|
| | 1225 | One-to-many relationships |
|---|
| | 1226 | ------------------------- |
|---|
| | 1227 | |
|---|
| | 1228 | Forward |
|---|
| | 1229 | ~~~~~~~ |
|---|
| | 1230 | |
|---|
| | 1231 | If a model has a ``ForeignKey``, instances of that model will have access to |
|---|
| | 1232 | the related (foreign) object via a simple attribute of the model. |
|---|
| | 1233 | |
|---|
| | 1234 | Example:: |
|---|
| | 1235 | |
|---|
| | 1236 | e = Entry.objects.get(id=2) |
|---|
| | 1237 | e.blog # Returns the related Blog object. |
|---|
| | 1238 | |
|---|
| | 1239 | You can get and set via a foreign-key attribute. As you may expect, changes to |
|---|
| | 1240 | the foreign key aren't saved to the database until you call ``save()``. |
|---|
| | 1241 | Example:: |
|---|
| | 1242 | |
|---|
| | 1243 | e = Entry.objects.get(id=2) |
|---|
| | 1244 | e.blog = some_blog |
|---|
| | 1245 | e.save() |
|---|
| | 1246 | |
|---|
| | 1247 | If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL`` |
|---|
| | 1248 | values), you can assign ``None`` to it. Example:: |
|---|
| | 1249 | |
|---|
| | 1250 | e = Entry.objects.get(id=2) |
|---|
| | 1251 | e.blog = None |
|---|
| | 1252 | e.save() # "UPDATE blog_entry SET blog_id = NULL ...;" |
|---|
| | 1253 | |
|---|
| | 1254 | Forward access to one-to-many relationships is cached the first time the |
|---|
| | 1255 | related object is accessed. Subsequent accesses to the foreign key on the same |
|---|
| | 1256 | object instance are cached. Example:: |
|---|
| | 1257 | |
|---|
| | 1258 | e = Entry.objects.get(id=2) |
|---|
| | 1259 | print e.blog # Hits the database to retrieve the associated Blog. |
|---|
| | 1260 | print e.blog # Doesn't hit the database; uses cached version. |
|---|
| | 1261 | |
|---|
| | 1262 | Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates |
|---|
| | 1263 | the cache of all one-to-many relationships ahead of time. Example:: |
|---|
| | 1264 | |
|---|
| | 1265 | e = Entry.objects.select_related().get(id=2) |
|---|
| | 1266 | print e.blog # Doesn't hit the database; uses cached version. |
|---|
| | 1267 | print e.blog # Doesn't hit the database; uses cached version. |
|---|
| | 1268 | |
|---|
| | 1269 | ``select_related()`` is documented in the "QuerySet methods that return new |
|---|
| | 1270 | QuerySets" section above. |
|---|
| | 1271 | |
|---|
| | 1272 | Backward |
|---|
| | 1273 | ~~~~~~~~ |
|---|
| | 1274 | |
|---|
| | 1275 | If a model has a ``ForeignKey``, instances of the foreign-key model will have |
|---|
| | 1276 | access to a ``Manager`` that returns all instances of the first model. By |
|---|
| | 1277 | default, this ``Manager`` is named ``FOO_set``, where ``FOO`` is the source |
|---|
| | 1278 | model name, lowercased. This ``Manager`` returns ``QuerySets``, which can be |
|---|
| | 1279 | filtered and manipulated as described in the "Retrieving objects" section |
|---|
| | 1280 | above. |
|---|
| | 1281 | |
|---|
| | 1282 | Example:: |
|---|
| | 1283 | |
|---|
| | 1284 | b = Blog.objects.get(id=1) |
|---|
| | 1285 | b.entry_set.all() # Returns all Entry objects related to Blog. |
|---|
| | 1286 | |
|---|
| | 1287 | # b.entry_set is a Manager that returns QuerySets. |
|---|
| | 1288 | b.entry_set.filter(headline__contains='Lennon') |
|---|
| | 1289 | b.entry_set.count() |
|---|
| | 1290 | |
|---|
| | 1291 | You can override the ``FOO_set`` name by setting the ``related_name`` |
|---|
| | 1292 | parameter in the ``ForeignKey()`` definition. For example, if the ``Entry`` |
|---|
| | 1293 | model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the |
|---|
| | 1294 | above example code would look like this:: |
|---|
| | 1295 | |
|---|
| | 1296 | b = Blog.objects.get(id=1) |
|---|
| | 1297 | b.entries.all() # Returns all Entry objects related to Blog. |
|---|
| | 1298 | |
|---|
| | 1299 | # b.entries is a Manager that returns QuerySets. |
|---|
| | 1300 | b.entries.filter(headline__contains='Lennon') |
|---|
| | 1301 | b.entries.count() |
|---|
| | 1302 | |
|---|
| | 1303 | You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must |
|---|
| | 1304 | be accessed from an instance. Example:: |
|---|
| | 1305 | |
|---|
| | 1306 | Blog.entry_set # Raises AttributeError: "Manager must be accessed via instance". |
|---|
| | 1307 | |
|---|
| | 1308 | In addition to the ``QuerySet`` methods defined in "Retrieving objects" above, |
|---|
| | 1309 | the ``ForeignKey`` ``Manager`` has these additional methods: |
|---|
| | 1310 | |
|---|
| | 1311 | * ``add(obj1, obj2, ...)``: Adds the specified model objects to the related |
|---|
| | 1312 | object set. |
|---|
| | 1313 | |
|---|
| | 1314 | Example:: |
|---|
| | 1315 | |
|---|
| | 1316 | b = Blog.objects.get(id=1) |
|---|
| | 1317 | e = Entry.objects.get(id=234) |
|---|
| | 1318 | b.entry_set.add(e) # Associates Entry e with Blog b. |
|---|
| | 1319 | |
|---|
| | 1320 | * ``create(**kwargs)``: Creates a new object, saves it and puts it in the |
|---|
| | 1321 | related object set. Returns the newly created object. |
|---|
| | 1322 | |
|---|
| | 1323 | Example:: |
|---|
| | 1324 | |
|---|
| | 1325 | b = Blog.objects.get(id=1) |
|---|
| | 1326 | e = b.entry_set.create(headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1)) |
|---|
| | 1327 | # No need to call e.save() at this point -- it's already been saved. |
|---|
| | 1328 | |
|---|
| | 1329 | This is equivalent to (but much simpler than):: |
|---|
| | 1330 | |
|---|
| | 1331 | b = Blog.objects.get(id=1) |
|---|
| | 1332 | e = Entry(blog=b, headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1)) |
|---|
| | 1333 | e.save() |
|---|
| | 1334 | |
|---|
| | 1335 | Note that there's no need to specify the keyword argument of the model |
|---|
| | 1336 | that defines the relationship. In the above example, we don't pass the |
|---|
| | 1337 | parameter ``blog`` to ``create()``. Django figures out that the new |
|---|
| | 1338 | ``Entry`` object's ``blog`` field should be set to ``b``. |
|---|
| | 1339 | |
|---|
| | 1340 | * ``remove(obj1, obj2, ...)``: Removes the specified model objects from the |
|---|
| | 1341 | related object set. |
|---|
| | 1342 | |
|---|
| | 1343 | Example:: |
|---|
| | 1344 | |
|---|
| | 1345 | b = Blog.objects.get(id=1) |
|---|
| | 1346 | e = Entry.objects.get(id=234) |
|---|
| | 1347 | b.entry_set.remove(e) # Disassociates Entry e from Blog b. |
|---|
| | 1348 | |
|---|
| | 1349 | In order to prevent database inconsistency, this method only exists on |
|---|
| | 1350 | ``ForeignKey``s where ``null=True``. If the related field can't be set to |
|---|
| | 1351 | ``None`` (``NULL``), then an object can't be removed from a relation |
|---|
| | 1352 | without being added to another. In the above example, removing ``e`` from |
|---|
| | 1353 | ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because |
|---|
| | 1354 | the ``blog`` ``ForeignKey`` doesn't have ``null=True``, this is invalid. |
|---|
| | 1355 | |
|---|
| | 1356 | * ``clear()``: Removes all objects from the related object set. |
|---|
| | 1357 | |
|---|
| | 1358 | Example:: |
|---|
| | 1359 | |
|---|
| | 1360 | b = Blog.objects.get(id=1) |
|---|
| | 1361 | b.entry_set.clear() |
|---|
| | 1362 | |
|---|
| | 1363 | Note this doesn't delete the related objects -- it just disassociates |
|---|
| | 1364 | them. |
|---|
| | 1365 | |
|---|
| | 1366 | Just like ``remove()``, ``clear()`` is only available on ``ForeignKey``s |
|---|
| | 1367 | where ``null=True``. |
|---|
| | 1368 | |
|---|
| | 1369 | To assign the members of a related set in one fell swoop, just assign to it |
|---|
| | 1370 | from any iterable object. Example:: |
|---|
| | 1371 | |
|---|
| | 1372 | b = Blog.objects.get(id=1) |
|---|
| | 1373 | b.entry_set = [e1, e2] |
|---|
| | 1374 | |
|---|
| | 1375 | If the ``clear()`` method is available, any pre-existing objects will be |
|---|
| | 1376 | removed from the ``entry_set`` before all objects in the iterable (in this |
|---|
| | 1377 | case, a list) are added to the set. If the ``clear()`` method is *not* |
|---|
| | 1378 | available, all objects in the iterable will be added without removing any |
|---|
| | 1379 | existing elements. |
|---|
| | 1380 | |
|---|
| | 1381 | Each "reverse" operation described in this section has an immediate effect on |
|---|
| | 1382 | the database. Every addition, creation and deletion is immediately and |
|---|
| | 1383 | automatically saved to the database. |
|---|
| | 1384 | |
|---|
| | 1385 | Many-to-many relationships |
|---|
| | 1386 | -------------------------- |
|---|
| | 1387 | |
|---|
| | 1388 | Both ends of a many-to-many relationship get automatic API access to the other |
|---|
| | 1389 | end. The API works just as a "backward" one-to-many relationship. See _Backward |
|---|
| | 1390 | above. |
|---|
| | 1391 | |
|---|
| | 1392 | The only difference is in the attribute naming: The model that defines the |
|---|
| | 1393 | ``ManyToManyField`` uses the attribute name of that field itself, whereas the |
|---|
| | 1394 | "reverse" model uses the lowercased model name of the original model, plus |
|---|
| | 1395 | ``'_set'`` (just like reverse one-to-many relationships). |
|---|
| | 1396 | |
|---|
| | 1397 | An example makes this easier to understand:: |
|---|
| | 1398 | |
|---|
| | 1399 | e = Entry.objects.get(id=3) |
|---|
| | 1400 | e.authors.all() # Returns all Author objects for this Entry. |
|---|
| | 1401 | e.authors.count() |
|---|
| | 1402 | e.authors.filter(name__contains='John') |
|---|
| | 1403 | |
|---|
| | 1404 | a = Author.objects.get(id=5) |
|---|
| | 1405 | a.entry_set.all() # Returns all Entry objects for this Author. |
|---|
| | 1406 | |
|---|
| | 1407 | Like ``ForeignKey``, ``ManyToManyField`` can specify ``related_name``. In the |
|---|
| | 1408 | above example, if the ``ManyToManyField`` in ``Entry`` had specified |
|---|
| | 1409 | ``related_name='entries'``, then each ``Author`` instance would have an |
|---|
| | 1410 | ``entries`` attribute instead of ``entry_set``. |
|---|
| | 1411 | |
|---|
| | 1412 | One-to-one relationships |
|---|
| 1224 | | If the related object is a single object, the descriptor acts |
|---|
| 1225 | | just as if the related object were an attribute:: |
|---|
| 1226 | | |
|---|
| 1227 | | # Obtain the existing poll |
|---|
| 1228 | | old_poll = mychoice.poll |
|---|
| 1229 | | # Set a new poll |
|---|
| 1230 | | mychoice.poll = new_poll |
|---|
| 1231 | | # Save the change |
|---|
| 1232 | | mychoice.save() |
|---|
| 1233 | | |
|---|
| 1234 | | Whenever a change is made to a Single Object Descriptor, save() |
|---|
| 1235 | | must be called to commit the change to the database. |
|---|
| 1236 | | |
|---|
| 1237 | | If no `related_name` parameter is defined, Django will use the |
|---|
| 1238 | | lower case version of the source model name as the name for the |
|---|
| 1239 | | related descriptor. For example, if the ``Choice`` model had |
|---|
| 1240 | | a field:: |
|---|
| 1241 | | |
|---|
| 1242 | | coordinator = models.OneToOneField(User) |
|---|
| 1243 | | |
|---|
| 1244 | | ... instances of the model ``User`` would be able to call: |
|---|
| 1245 | | |
|---|
| 1246 | | old_choice = myuser.choice |
|---|
| 1247 | | myuser.choice = new_choice |
|---|
| 1248 | | |
|---|
| 1249 | | By default, relations do not allow values of None; if you attempt |
|---|
| 1250 | | to assign None to a Single Object Descriptor, an AttributeError |
|---|
| 1251 | | will be thrown. However, if the relation has 'null=True' set |
|---|
| 1252 | | (i.e., the database will allow NULLs for the relation), None can |
|---|
| 1253 | | be assigned and returned by the descriptor to represent empty |
|---|
| 1254 | | relations. |
|---|
| 1255 | | |
|---|
| 1256 | | Access to Single Object Descriptors is cached. The first time |
|---|
| 1257 | | a descriptor on an instance is accessed, the database will be |
|---|
| 1258 | | queried, and the result stored. Subsequent attempts to access |
|---|
| 1259 | | the descriptor on the same instance will use the cached value. |
|---|
| 1260 | | |
|---|
| 1261 | | Object set descriptor |
|---|
| 1262 | | --------------------- |
|---|
| 1263 | | |
|---|
| 1264 | | An Object Set Descriptor acts just like the Manager - as an initial Query |
|---|
| 1265 | | Set describing the set of objects related to an instance. As such, any |
|---|
| 1266 | | query refining technique (filter, exclude, etc) can be used on the Object |
|---|
| 1267 | | Set descriptor. This also means that Object Set Descriptor cannot be evaluated |
|---|
| 1268 | | directly - the ``all()`` method must be used to produce a Query Set that |
|---|
| 1269 | | can be evaluated. |
|---|
| 1270 | | |
|---|
| 1271 | | If no ``related_name`` parameter is defined, Django will use the lower case |
|---|
| 1272 | | version of the source model name appended with `_set` as the name for the |
|---|
| 1273 | | related descriptor. For example, every ``Poll`` object has a ``choice_set`` |
|---|
| 1274 | | descriptor. |
|---|
| 1275 | | |
|---|
| 1276 | | The Object Set Descriptor has utility methods to add objects to the |
|---|
| 1277 | | related object set: |
|---|
| 1278 | | |
|---|
| 1279 | | ``add(obj1, obj2, ...)`` |
|---|
| 1280 | | Add the specified objects to the related object set. |
|---|
| 1281 | | |
|---|
| 1282 | | ``create(\**kwargs)`` |
|---|
| 1283 | | Create a new object, and put it in the related object set. See |
|---|
| 1284 | | _`Creating new objects` |
|---|
| 1285 | | |
|---|
| 1286 | | The Object Set Descriptor may also have utility methods to remove objects |
|---|
| 1287 | | from the related object set: |
|---|
| 1288 | | |
|---|
| 1289 | | ``remove(obj1, obj2, ...)`` |
|---|
| 1290 | | Remove the specified objects from the related object set. |
|---|
| 1291 | | |
|---|
| 1292 | | ``clear()`` |
|---|
| 1293 | | Remove all objects from the related object set. |
|---|
| 1294 | | |
|---|
| 1295 | | These two removal methods will not exist on ForeignKeys where ``Null=False`` |
|---|
| 1296 | | (such as in the Poll example). This is to prevent database inconsistency - if |
|---|
| 1297 | | the related field cannot be set to None, then an object cannot be removed |
|---|
| 1298 | | from one relation without adding it to another. |
|---|
| 1299 | | |
|---|
| 1300 | | The members of a related object set can be assigned from any iterable object. |
|---|
| 1301 | | For example:: |
|---|
| 1302 | | |
|---|
| 1303 | | mypoll.choice_set = [choice1, choice2] |
|---|
| 1304 | | |
|---|
| 1305 | | If the ``clear()`` method is available, any pre-existing objects will be removed |
|---|
| 1306 | | from the Object Set before all objects in the iterable (in this case, a list) |
|---|
| 1307 | | are added to the choice set. If the ``clear()`` method is not available, all |
|---|
| 1308 | | objects in the iterable will be added without removing any existing elements. |
|---|
| 1309 | | |
|---|
| 1310 | | Each of these operations on the Object Set Descriptor has immediate effect |
|---|
| 1311 | | on the database - every add, create and remove is immediately and |
|---|
| 1312 | | automatically saved to the database. |
|---|
| 1313 | | |
|---|
| 1314 | | Relationships and queries |
|---|
| 1315 | | ========================= |
|---|
| 1316 | | |
|---|
| 1317 | | When composing a ``filter`` or ``exclude`` refinement, it may be necessary to |
|---|
| 1318 | | include conditions that span relationships. Relations can be followed as deep |
|---|
| 1319 | | as required - just add descriptor names, separated by double underscores, to |
|---|
| 1320 | | describe the full path to the query attribute. The query:: |
|---|
| 1321 | | |
|---|
| 1322 | | Foo.objects.filter(name1__name2__name3__attribute__lookup=value) |
|---|
| 1323 | | |
|---|
| 1324 | | ... is interpreted as 'get every Foo that has a name1 that has a name2 that |
|---|
| 1325 | | has a name3 that has an attribute with lookup matching value'. In the Poll |
|---|
| 1326 | | example:: |
|---|
| 1327 | | |
|---|
| 1328 | | Choice.objects.filter(poll__slug__startswith="eggs") |
|---|
| 1329 | | |
|---|
| 1330 | | ... describes the set of choices for which the related poll has a slug |
|---|
| 1331 | | attribute that starts with "eggs". Django automatically composes the joins |
|---|
| 1332 | | and conditions required for the SQL query. |
|---|
| 1333 | | |
|---|
| 1334 | | Creating new related objects |
|---|
| 1335 | | ============================ |
|---|
| 1336 | | |
|---|
| 1337 | | Related objects are created using the ``create()`` convenience function on |
|---|
| 1338 | | the descriptor Manager for relation:: |
|---|
| 1339 | | |
|---|
| 1340 | | >>> p.choice_set.create(choice="Over easy", votes=0) |
|---|
| 1341 | | >>> p.choice_set.create(choice="Scrambled", votes=0) |
|---|
| 1342 | | >>> p.choice_set.create(choice="Fertilized", votes=0) |
|---|
| 1343 | | >>> p.choice_set.create(choice="Poached", votes=0) |
|---|
| 1344 | | >>> p.choice_set.count() |
|---|
| 1345 | | 4 |
|---|
| 1346 | | |
|---|
| 1347 | | Each of those ``create()`` methods is equivalent to (but much simpler than):: |
|---|
| 1348 | | |
|---|
| 1349 | | >>> c = Choice(poll_id=p.id, choice="Over easy", votes=0) |
|---|
| 1350 | | >>> c.save() |
|---|
| 1351 | | |
|---|
| 1352 | | Note that when using the `create()`` method, you do not give any value |
|---|
| 1353 | | for the ``id`` field, nor do you give a value for the field that stores |
|---|
| 1354 | | the relation (``poll_id`` in this case). |
|---|
| 1355 | | |
|---|
| 1356 | | The ``create()`` method always returns the newly created object. |
|---|
| | 1415 | The semantics of one-to-one relationships will be changing soon, so we don't |
|---|
| | 1416 | recommend you use them. |
|---|
| | 1417 | |
|---|
| | 1418 | How are the backward relationships possible? |
|---|
| | 1419 | -------------------------------------------- |
|---|
| | 1420 | |
|---|
| | 1421 | Other object-relational mappers require you to define relationships on both |
|---|
| | 1422 | sides. The Django developers believe this is a violation of the DRY (Don't |
|---|
| | 1423 | Repeat Yourself) principle, so Django only requires you to define the |
|---|
| | 1424 | relationship on one end. |
|---|
| | 1425 | |
|---|
| | 1426 | But how is this possible, given that a model class doesn't know which other |
|---|
| | 1427 | model classes are related to it until those other model classes are loaded? |
|---|
| | 1428 | |
|---|
| | 1429 | The answer lies in the ``INSTALLED_APPS`` setting. The first time any model is |
|---|
| | 1430 | loaded, Django iterates over every model in ``INSTALLED_APPS`` and creates the |
|---|
| | 1431 | backward relationships in memory as needed. Essentially, one of the functions |
|---|
| | 1432 | of ``INSTALLED_APPS`` is to tell Django the entire model domain. |
|---|