| | 2040 | One-to-one relationships |
|---|
| | 2041 | ------------------------ |
|---|
| | 2042 | |
|---|
| | 2043 | One-to-one relationships are very similar to Many-to-one relationships. |
|---|
| | 2044 | If you define a OneToOneField on your model, instances of that model will have |
|---|
| | 2045 | access to the related object via a simple attribute of the model. |
|---|
| | 2046 | |
|---|
| | 2047 | For example:: |
|---|
| | 2048 | |
|---|
| | 2049 | class EntryDetail(models.Model): |
|---|
| | 2050 | entry = models.OneToOneField(Entry) |
|---|
| | 2051 | details = models.TextField() |
|---|
| | 2052 | |
|---|
| | 2053 | ed = EntryDetail.objects.get(id=2) |
|---|
| | 2054 | ed.entry # Returns the related Entry object. |
|---|
| | 2055 | |
|---|
| | 2056 | The difference comes in reverse queries. The related model in a One-to-one |
|---|
| | 2057 | relationship also has access to a ``Manager`` object; however, that ``Manager`` |
|---|
| | 2058 | represents a single object, rather than a collection of objects:: |
|---|
| | 2059 | |
|---|
| | 2060 | e = Entry.objects.get(id=2) |
|---|
| | 2061 | e.entrydetail # returns the related EntryDetail object |
|---|
| | 2062 | |
|---|
| | 2063 | If no object has been assigned to this relationship, Django will raise |
|---|
| | 2064 | a ``DoesNotExist`` exception. |
|---|
| | 2065 | |
|---|
| | 2066 | Instances can be assigned to the reverse relationship in the same way as |
|---|
| | 2067 | you would assign the forward relationship:: |
|---|
| | 2068 | |
|---|
| | 2069 | e.entrydetail = ed |
|---|
| | 2070 | |
|---|