aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide/fields.md
diff options
context:
space:
mode:
authorTom Christie2013-01-15 17:53:24 +0000
committerTom Christie2013-01-15 17:53:24 +0000
commit71e55cc4f6300959398f7aef4a8d91b6a6a2af57 (patch)
tree68c2080034263d897741da33cbc5e09746006257 /docs/api-guide/fields.md
parent52847a215d4e8de88e81d9ae79ce8bee9a36a9a2 (diff)
parente1076cfb49b6293aa837cf7bdb4c11988892c598 (diff)
downloaddjango-rest-framework-71e55cc4f6300959398f7aef4a8d91b6a6a2af57.tar.bz2
Merge with latest master
Diffstat (limited to 'docs/api-guide/fields.md')
-rw-r--r--docs/api-guide/fields.md193
1 files changed, 107 insertions, 86 deletions
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 7e117df7..5bc8f7f7 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,11 +2,11 @@
# Serializer fields
-> Flat is better than nested.
+> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it -- normalizing it to a consistent format.
>
-> — [The Zen of Python][cite]
+> — [Django documentation][cite]
-Serializer fields handle converting between primative values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
+Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
---
@@ -14,6 +14,51 @@ Serializer fields handle converting between primative values and internal dataty
---
+## Core arguments
+
+Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
+
+### `source`
+
+The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`.
+
+The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the `PaginationSerializer` class for an example.)
+
+Defaults to the name of the field.
+
+### `read_only`
+
+Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.
+
+Defaults to `False`
+
+### `required`
+
+Normally an error will be raised if a field is not supplied during deserialization.
+Set to false if this field is not required to be present during deserialization.
+
+Defaults to `True`.
+
+### `default`
+
+If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all.
+
+### `validators`
+
+A list of Django validators that should be used to validate deserialized values.
+
+### `error_messages`
+
+A dictionary of error codes to error messages.
+
+### `widget`
+
+Used only if rendering the field to HTML.
+This argument sets the widget that should be used to render the field.
+
+
+---
+
# Generic Fields
These generic fields are used for representing arbitrary model fields or the output of model methods.
@@ -51,9 +96,9 @@ Would produce output similar to:
'expired': True
}
-By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary.
+By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
-You can customize this behaviour by overriding the `.to_native(self, value)` method.
+You can customize this behavior by overriding the `.to_native(self, value)` method.
## WritableField
@@ -65,6 +110,24 @@ A generic field that can be tied to any arbitrary model field. The `ModelField`
**Signature:** `ModelField(model_field=<Django ModelField class>)`
+## SerializerMethodField
+
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
+ from rest_framework import serializers
+ from django.contrib.auth.models import User
+ from django.utils.timezone import now
+
+ class UserSerializer(serializers.ModelSerializer):
+
+ days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
+
---
# Typed Fields
@@ -86,6 +149,18 @@ or `django.db.models.fields.TextField`.
**Signature:** `CharField(max_length=None, min_length=None)`
+## URLField
+
+Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
+
+**Signature:** `CharField(max_length=200, min_length=None)`
+
+## SlugField
+
+Corresponds to `django.db.models.fields.SlugField`.
+
+**Signature:** `CharField(max_length=50, min_length=None)`
+
## ChoiceField
A field that can accept a value out of a limited set of choices.
@@ -96,6 +171,16 @@ A text representation, validates the text to be a valid e-mail address.
Corresponds to `django.db.models.fields.EmailField`
+## RegexField
+
+A text representation, that validates the given value matches against a certain regular expression.
+
+Uses Django's `django.core.validators.RegexValidator` for validation.
+
+Corresponds to `django.forms.fields.RegexField`
+
+**Signature:** `RegexField(regex, max_length=None, min_length=None)`
+
## DateField
A date representation.
@@ -120,96 +205,32 @@ A floating point representation.
Corresponds to `django.db.models.fields.FloatField`.
----
-
-# Relational Fields
+## FileField
-Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
+A file representation. Performs Django's standard FileField validation.
-## RelatedField
+Corresponds to `django.forms.fields.FileField`.
-This field can be applied to any of the following:
+**Signature:** `FileField(max_length=None, allow_empty_file=False)`
-* A `ForeignKey` field.
-* A `OneToOneField` field.
-* A reverse OneToOne relationship
-* Any other "to-one" relationship.
+ - `max_length` designates the maximum length for the file name.
+
+ - `allow_empty_file` designates if empty files are allowed.
-By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+## ImageField
-You can customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
+An image representation.
-## ManyRelatedField
+Corresponds to `django.forms.fields.ImageField`.
-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.
+Requires the `PIL` package.
-By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+Signature and validation is the same as with `FileField`.
-For example, given the following models:
-
- class TaggedItem(models.Model):
- """
- Tags arbitrary model instances using a generic relation.
-
- 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)
-
-And a model serializer defined like this:
-
- class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
-
- class Meta:
- model = Bookmark
- exclude = ('id',)
-
-Then an example output format for a Bookmark instance would be:
-
- {
- 'tags': [u'django', u'python'],
- 'url': u'https://www.djangoproject.com/'
- }
-
-## PrimaryKeyRelatedField
-
-As with `RelatedField` field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
-
-`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
-
-Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
-
-## ManyPrimaryKeyRelatedField
-
-As with `RelatedField` field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
-
-`PrimaryKeyRelatedField` will represent the target of the field using their primary key.
-
-Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
-
-## HyperlinkedRelatedField
-
-## ManyHyperlinkedRelatedField
+---
-## HyperLinkedIdentityField
+**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
+Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
-[cite]: http://www.python.org/dev/peps/pep-0020/
+[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
+[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS