relations.txt 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. .. _ref-models-relations:
  2. =========================
  3. Related objects reference
  4. =========================
  5. Extra methods on managers when used in a ForeignKey context
  6. ===========================================================
  7. .. currentmodule:: django.db.models
  8. .. method:: QuerySet.add(obj1, [obj2, ...])
  9. Adds the specified model objects to the related object set.
  10. Example::
  11. >>> b = Blog.objects.get(id=1)
  12. >>> e = Entry.objects.get(id=234)
  13. >>> b.entry_set.add(e) # Associates Entry e with Blog b.
  14. .. method:: QuerySet.create(**kwargs)
  15. Creates a new object, saves it and puts it in the related object set.
  16. Returns the newly created object::
  17. >>> b = Blog.objects.get(id=1)
  18. >>> e = b.entry_set.create(
  19. ... headline='Hello',
  20. ... body_text='Hi',
  21. ... pub_date=datetime.date(2005, 1, 1)
  22. ... )
  23. # No need to call e.save() at this point -- it's already been saved.
  24. This is equivalent to (but much simpler than)::
  25. >>> b = Blog.objects.get(id=1)
  26. >>> e = Entry(
  27. .... blog=b,
  28. .... headline='Hello',
  29. .... body_text='Hi',
  30. .... pub_date=datetime.date(2005, 1, 1)
  31. .... )
  32. >>> e.save()
  33. Note that there's no need to specify the keyword argument of the model that
  34. defines the relationship. In the above example, we don't pass the parameter
  35. ``blog`` to ``create()``. Django figures out that the new ``Entry`` object's
  36. ``blog`` field should be set to ``b``.
  37. .. method:: QuerySet.remove(obj1, [obj2, ...])
  38. Removes the specified model objects from the related object set::
  39. >>> b = Blog.objects.get(id=1)
  40. >>> e = Entry.objects.get(id=234)
  41. >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
  42. In order to prevent database inconsistency, this method only exists on
  43. ``ForeignKey`` objects where ``null=True``. If the related field can't be
  44. set to ``None`` (``NULL``), then an object can't be removed from a relation
  45. without being added to another. In the above example, removing ``e`` from
  46. ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because the
  47. ``blog`` ``ForeignKey`` doesn't have ``null=True``, this is invalid.
  48. .. method:: QuerySet.clear()
  49. Removes all objects from the related object set::
  50. >>> b = Blog.objects.get(id=1)
  51. >>> b.entry_set.clear()
  52. Note this doesn't delete the related objects -- it just disassociates them.
  53. Just like ``remove()``, ``clear()`` is only available on ``ForeignKey``\s
  54. where ``null=True``.