From e682bfa54efc391df4d6bb7cf78a2089213b8d6b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 28 Jan 2013 08:01:54 +0000 Subject: Drop unneccessary `source=` argument. --- docs/api-guide/relations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 351b5e09..9f5a04b2 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -67,7 +67,7 @@ For example, given the following models: And a model serializer defined like this: class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.ManyRelatedField(source='tags') + tags = serializers.ManyRelatedField() class Meta: model = Bookmark -- cgit v1.2.3 From 15c8fd96ef34cb48bd85f7f886c8c0db71c73cff Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 7 Feb 2013 23:11:12 +0000 Subject: Docs for related fields, with lots of examples. --- docs/api-guide/relations.md | 349 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 279 insertions(+), 70 deletions(-) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 9f5a04b2..aedff96e 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -12,128 +12,337 @@ Relational fields are used to represent model relationships. They can be applie --- -**Note:** The relational fields are declared in `relations.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. +**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.`. --- -## RelatedField - -This field can be applied to any of the following: - -* A `ForeignKey` field. -* A `OneToOneField` field. -* A reverse OneToOne relationship -* Any other "to-one" relationship. - -By default `RelatedField` will represent the target of the field using it's `__unicode__` method. - -You can customize this behavior by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method. +# API Reference -## ManyRelatedField +In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. -This field can be applied to any of the following: - -* A `ManyToManyField` field. -* A reverse ManyToMany relationship. -* A reverse ForeignKey relationship -* Any other "to-many" relationship. - -By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method. + class Album(models.Model): + album_name = models.CharField(max_length=100) + artist = models.CharField(max_length=100) -For example, given the following models: + class Track(models.Model): + album = models.ForeignKey(Album, related_name='tracks') + order = models.IntegerField() + title = models.CharField(max_length=100) + duration = models.IntegerField() - class TaggedItem(models.Model): - """ - Tags arbitrary model instances using a generic relation. + class Meta: + unique_together = ('album', 'order') - See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ - """ - tag = models.SlugField() - content_type = models.ForeignKey(ContentType) - object_id = models.PositiveIntegerField() - content_object = GenericForeignKey('content_type', 'object_id') - def __unicode__(self): - return self.tag - - - class Bookmark(models.Model): - """ - A bookmark consists of a URL, and 0 or more descriptive tags. - """ - url = models.URLField() - tags = GenericRelation(TaggedItem) + return '%d: %s' % (self.order, self.title) -And a model serializer defined like this: +## RelatedField - class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.ManyRelatedField() +`RelatedField` may be used to represent the target of the relationship using it's `__unicode__` method. +For example, the following serializer. + + class AlbumSerializer(serializer.ModelSerializer): + tracks = RelatedField(many=True) + class Meta: - model = Bookmark - exclude = ('id',) + fields = ('album_name', 'artist', 'tracks') -Then an example output format for a Bookmark instance would be: +Would serialize to the following representation. { - 'tags': [u'django', u'python'], - 'url': u'https://www.djangoproject.com/' + 'album_name': 'Things We Lost In The Fire', + 'artist': 'Low' + 'tracks': [ + '1: Sunflower', + '2: Whitetail', + '3: Dinosaur Act', + ... + ] } -## PrimaryKeyRelatedField -## ManyPrimaryKeyRelatedField +This field is read only. -`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key. +## PrimaryKeyRelatedField -By default these fields are read-write, although you can change this behavior using the `read_only` flag. +`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. -**Arguments**: - -* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships. +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = PrimaryKeyRelatedField(many=True, read_only=True) + + class Meta: + fields = ('album_name', 'artist', 'tracks') -## SlugRelatedField -## ManySlugRelatedField +Would serialize to a representation like this: -`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug. + { + 'album_name': 'The Roots', + 'artist': 'Undun' + 'tracks': [ + 89, + 90, + 91, + ... + ] + } -By default these fields read-write, although you can change this behavior using the `read_only` flag. +By default this field is read-write, although you can change this behavior using the `read_only` flag. **Arguments**: -* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. ## HyperlinkedRelatedField -## ManyHyperlinkedRelatedField -`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink. +`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. -By default, `HyperlinkedRelatedField` is read-write, although you can change this behavior using the `read_only` flag. +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = HyperlinkedRelatedField(many=True, read_only=True, + view_name='track-detail') + + class Meta: + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Graceland', + 'artist': 'Paul Simon' + 'tracks': [ + 'http://www.example.com/api/tracks/45', + 'http://www.example.com/api/tracks/46', + 'http://www.example.com/api/tracks/47', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. **required**. -* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. * `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. * `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. + +## SlugRelatedField + +`SlugRelatedField` may be used to represent the target of the relationship using a field on the target. + +For example, the following serializer: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') + + class Meta: + fields = ('album_name', 'artist', 'tracks') + +Would serialize to a representation like this: + + { + 'album_name': 'Dear John', + 'artist': 'Loney Dear' + 'tracks': [ + 'Airport Surroundings', + 'Everything Turns to You', + 'I Was Only Going Out', + ... + ] + } + +By default this field is read-write, although you can change this behavior using the `read_only` flag. + +When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`. + +**Arguments**: + +* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. +* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships. ## HyperLinkedIdentityField -This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. +This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: + + class AlbumSerializer(serializers.HyperlinkedModelSerializer): + track_listing = HyperLinkedIdentityField(view_name='track-list') + + class Meta: + fields = ('album_name', 'artist', 'track_listing') + +Would serialize to a representation like this: + { + 'album_name': 'The Eraser', + 'artist': 'Thom Yorke' + 'track_listing': 'http://www.example.com/api/track_list/12', + } + This field is always read-only. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. **required**. -* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. * `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. * `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. * `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. + +## Nested relationships + +Nested relationships can be expressed by using serializers as fields. For example: + + class TrackSerializer(serializer.ModelSerializer): + class Meta: + fields = ('order', 'title') + + class AlbumSerializer(serializer.ModelSerializer): + tracks = TrackSerializer(many=True) + + class Meta: + fields = ('album_name', 'artist', 'tracks') + +Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. + +## Custom relational fields + +To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. + + class TrackListingField(serializers.RelatedField): + def to_native(self, value): + return 'Track %d: %s' % (value.ordering, value.name) + +If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition. + +# Further notes + +## Reverse relations + +Note that reverse relationships are not automatically generated by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you cannot simply add it to the fields list. + +**The following will not work:** + + class AlbumSerializer(serializer.ModelSerializer): + class Meta: + fields = ('tracks', ...) + +Instead, you must explicitly add it to the serializer. For example: + + class AlbumSerializer(serializer.ModelSerializer): + tracks = serializers.PrimaryKeyRelationship(many=True) + ... + +By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work. + +The best way to ensure this is typically to make sure that the relationship on the model definition has it's `related_name` argument properly set. For example: + + class Track(models.Model): + album = models.ForeignKey(Album, related_name='tracks') + ... + +Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. + + class AlbumSerializer(serializer.ModelSerializer): + tracks = serializers.PrimaryKeyRelationship(many=True, source='track_set') + +See the Django documentation on [reverse relationships][reverse-relationships] for more details. + +## Generic relationships + +If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want serialize the targets of the relationship. + +For example, given the following model for a tag, which has a generic relationship with other arbitrary models: + + class TaggedItem(models.Model): + """ + Tags arbitrary model instances using a generic relation. + + See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ + """ + tag_name = models.SlugField() + content_type = models.ForeignKey(ContentType) + object_id = models.PositiveIntegerField() + tagged_object = GenericForeignKey('content_type', 'object_id') + + def __unicode__(self): + return self.tag + +And the following two models, which may be have associated tags: + + class Bookmark(models.Model): + """ + A bookmark consists of a URL, and 0 or more descriptive tags. + """ + url = models.URLField() + tags = GenericRelation(TaggedItem) + + + class Note(models.Model): + """ + A note consists of some text, and 0 or more descriptive tags. + """ + text = models.CharField(max_length=1000) + tags = GenericRelation(TaggedItem) + +We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized. + + class TaggedObjectRelatedField(serializers.RelatedField): + """ + A custom field to use for the `tagged_object` generic relationship. + """ + + def to_native(self, value): + """ + Serialize tagged objects to a simple textual representation. + """ + if isinstance(value, Bookmark): + return 'Bookmark: ' + value.url + elif isinstance(value, Note): + return 'Note: ' + value.text + raise Exception('Unexpected type of tagged object') + +If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method: + + def to_native(self, value): + """ + Serialize bookmark instances using a bookmark serializer, + and note instances using a note serializer. + """ + if isinstance(value, Bookmark): + serializer = BookmarkSerializer(value) + elif isinstance(value, Note): + serializer = NoteSerializer(value) + else: + raise Exception('Unexpected type of tagged object') + + return serializer.data + +Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. + +For more information see [the Django documentation on generic relations][generic-relations]. + +--- + +## Deprecated relational fields + +The following classes have been deprecated, in favor of the `many=` syntax. +They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default. +In the 2.3 release, this warning will be escalated to a `DeprecationWarning`. +In the 2.4 release, they will be removed entirely. + +* `ManyRelatedField` +* `ManyPrimaryKeyRelatedField` +* `ManyHyperlinkedRelatedField` +* `ManySlugRelatedField` [cite]: http://lwn.net/Articles/193245/ +[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward +[generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 -- cgit v1.2.3 From fd57978cb757597b82b58df78c52dc98eaed875e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 8 Feb 2013 09:01:45 +0000 Subject: Add missing `model =` to serializer classes in docs --- docs/api-guide/relations.md | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index aedff96e..c5da084b 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -46,6 +46,7 @@ For example, the following serializer. tracks = RelatedField(many=True) class Meta: + model = Album fields = ('album_name', 'artist', 'tracks') Would serialize to the following representation. @@ -73,6 +74,7 @@ For example, the following serializer: tracks = PrimaryKeyRelatedField(many=True, read_only=True) class Meta: + model = Album fields = ('album_name', 'artist', 'tracks') Would serialize to a representation like this: @@ -106,6 +108,7 @@ For example, the following serializer: view_name='track-detail') class Meta: + model = Album fields = ('album_name', 'artist', 'tracks') Would serialize to a representation like this: @@ -143,6 +146,7 @@ For example, the following serializer: tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') class Meta: + model = Album fields = ('album_name', 'artist', 'tracks') Would serialize to a representation like this: @@ -176,6 +180,7 @@ This field can be applied as an identity relationship, such as the `'url'` field track_listing = HyperLinkedIdentityField(view_name='track-list') class Meta: + model = Album fields = ('album_name', 'artist', 'track_listing') Would serialize to a representation like this: @@ -208,6 +213,7 @@ Nested relationships can be expressed by using serializers as fields. For examp tracks = TrackSerializer(many=True) class Meta: + model = Album fields = ('album_name', 'artist', 'tracks') Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. -- cgit v1.2.3 From 0997ce9fc20cd9ff8e63246c3892d28b411bf857 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 10 Feb 2013 16:44:32 +0000 Subject: Improve relations documentation. --- docs/api-guide/relations.md | 93 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 79 insertions(+), 14 deletions(-) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index c5da084b..25fca475 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -32,6 +32,7 @@ In order to explain the various types of relational fields, we'll use a couple o class Meta: unique_together = ('album', 'order') + order_by = 'order' def __unicode__(self): return '%d: %s' % (self.order, self.title) @@ -64,6 +65,10 @@ Would serialize to the following representation. This field is read only. +**Arguments**: + +* `many` - If applied to a to-many relationship, you should set this argument to `True`. + ## PrimaryKeyRelatedField `PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. @@ -94,8 +99,9 @@ By default this field is read-write, although you can change this behavior using **Arguments**: -* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. +* `many` - If applied to a to-many relationship, you should set this argument to `True`. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. +* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. ## HyperlinkedRelatedField @@ -129,6 +135,7 @@ By default this field is read-write, although you can change this behavior using **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. **required**. +* `many` - If applied to a to-many relationship, you should set this argument to `True`. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. @@ -168,16 +175,17 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e **Arguments**: -* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. +* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required** +* `many` - If applied to a to-many relationship, you should set this argument to `True`. +* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. -* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships. -## HyperLinkedIdentityField +## HyperlinkedIdentityField This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): - track_listing = HyperLinkedIdentityField(view_name='track-list') + track_listing = HyperlinkedIdentityField(view_name='track-list') class Meta: model = Album @@ -201,12 +209,23 @@ This field is always read-only. * `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. -## Nested relationships +--- + +# Nested relationships + +Nested relationships can be expressed by using serializers as fields. + +If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. + +Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. + +## Example -Nested relationships can be expressed by using serializers as fields. For example: +For example, the following serializer: class TrackSerializer(serializer.ModelSerializer): class Meta: + model = Track fields = ('order', 'title') class AlbumSerializer(serializer.ModelSerializer): @@ -216,17 +235,57 @@ Nested relationships can be expressed by using serializers as fields. For examp model = Album fields = ('album_name', 'artist', 'tracks') -Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. +Would serialize to a nested representation like this: -## Custom relational fields + { + 'album_name': 'The Grey Album', + 'artist': 'Danger Mouse' + 'tracks': [ + {'order': 1, 'title': 'Public Service Annoucement'}, + {'order': 2, 'title': 'What More Can I Say'}, + {'order': 3, 'title': 'Encore'}, + ... + ], + } + +# Custom relational fields To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. +If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition. + +## Example + +For, example, we could define a relational field, to serialize a track to a custom string representation, using it's ordering, title, and duration. + + import time + class TrackListingField(serializers.RelatedField): def to_native(self, value): - return 'Track %d: %s' % (value.ordering, value.name) + duration = time.strftime('%M:%S', time.gmtime(value.duration)) + return 'Track %d: %s (%s)' % (value.order, value.name, duration) -If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition. + class AlbumSerializer(serializer.ModelSerializer): + tracks = TrackListingField(many=True) + + class Meta: + model = Album + fields = ('album_name', 'artist', 'tracks') + +This custom field would then serialize to the following representation. + + { + 'album_name': 'Sometimes I Wish We Were an Eagle', + 'artist': 'Bill Callahan' + 'tracks': [ + 'Track 1: Jim Cain (04:39)', + 'Track 2: Eid Ma Clack Shaw (04:19)', + 'Track 3: The Wind and the Dove (04:34)', + ... + ] + } + +--- # Further notes @@ -337,18 +396,24 @@ For more information see [the Django documentation on generic relations][generic --- -## Deprecated relational fields +## Deprecated APIs The following classes have been deprecated, in favor of the `many=` syntax. They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default. -In the 2.3 release, this warning will be escalated to a `DeprecationWarning`. -In the 2.4 release, they will be removed entirely. * `ManyRelatedField` * `ManyPrimaryKeyRelatedField` * `ManyHyperlinkedRelatedField` * `ManySlugRelatedField` +The `null=` flag has been deprecated in favor of the `required=` flag. It will continue to function, but will raise a `PendingDeprecationWarning`. + +In the 2.3 release, these warnings will be escalated to a `DeprecationWarning`, which is loud by default. +In the 2.4 release, these parts of the API will be removed entirely. + +For more details see the [2.2 release announcement][2.2-announcement]. + [cite]: http://lwn.net/Articles/193245/ [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 +[2.2-announcement]: ../topics/2.2-announcement.md -- cgit v1.2.3 From 66a6ffaf957405691d0714fc422b46a6927639a7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 19 Feb 2013 17:09:28 +0000 Subject: Fix typos. --- docs/api-guide/relations.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 25fca475..5a9d74b0 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -43,7 +43,7 @@ In order to explain the various types of relational fields, we'll use a couple o For example, the following serializer. - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = RelatedField(many=True) class Meta: @@ -75,7 +75,7 @@ This field is read only. For example, the following serializer: - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = PrimaryKeyRelatedField(many=True, read_only=True) class Meta: @@ -109,7 +109,7 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = HyperlinkedRelatedField(many=True, read_only=True, view_name='track-detail') @@ -149,7 +149,7 @@ By default this field is read-write, although you can change this behavior using For example, the following serializer: - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = SlugRelatedField(many=True, read_only=True, slug_field='title') class Meta: @@ -223,12 +223,12 @@ Note that nested relationships are currently read-only. For read-write relation For example, the following serializer: - class TrackSerializer(serializer.ModelSerializer): + class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title') - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: @@ -265,7 +265,7 @@ For, example, we could define a relational field, to serialize a track to a cust duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: @@ -295,13 +295,13 @@ Note that reverse relationships are not automatically generated by the `ModelSer **The following will not work:** - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ('tracks', ...) Instead, you must explicitly add it to the serializer. For example: - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelationship(many=True) ... @@ -315,7 +315,7 @@ The best way to ensure this is typically to make sure that the relationship on t Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. - class AlbumSerializer(serializer.ModelSerializer): + class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelationship(many=True, source='track_set') See the Django documentation on [reverse relationships][reverse-relationships] for more details. -- cgit v1.2.3 From c5cf51cf511c84ab3e446376ff38170dcd421958 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 19 Feb 2013 17:16:48 +0000 Subject: Fix typos. --- docs/api-guide/relations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/api-guide/relations.md') diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 5a9d74b0..623fe1a9 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -302,7 +302,7 @@ Note that reverse relationships are not automatically generated by the `ModelSer Instead, you must explicitly add it to the serializer. For example: class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelationship(many=True) + tracks = serializers.PrimaryKeyRelatedField(many=True) ... By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work. @@ -316,7 +316,7 @@ The best way to ensure this is typically to make sure that the relationship on t Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. class AlbumSerializer(serializers.ModelSerializer): - tracks = serializers.PrimaryKeyRelationship(many=True, source='track_set') + tracks = serializers.PrimaryKeyRelatedField(many=True, source='track_set') See the Django documentation on [reverse relationships][reverse-relationships] for more details. -- cgit v1.2.3