django-rest-framework/docs/api-guide/fields.md

283 lines
9.6 KiB
Markdown
Raw Normal View History

<a class="github" href="fields.py"></a>
# Serializer fields
> Flat is better than nested.
>
> &mdash; [The Zen of Python][cite]
2012-10-05 22:26:57 +04:00
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.
---
2012-10-05 20:02:33 +04:00
**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
2012-10-29 00:18:02 +04:00
---
## 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.
2012-10-29 00:21:45 +04:00
### `read_only`
2012-10-29 00:18:02 +04:00
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing 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 behaviour 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.
2012-10-05 22:26:57 +04:00
---
2012-10-05 20:02:33 +04:00
# Generic Fields
These generic fields are used for representing arbitrary model fields or the output of model methods.
## Field
A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations.
For example, using the following model.
class Account(models.Model):
owner = models.ForeignKey('auth.user')
name = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
payment_expiry = models.DateTimeField()
def has_expired(self):
now = datetime.datetime.now()
return now > self.payment_expiry
A serializer definition that looked like this:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
expired = Field(source='has_expired')
class Meta:
fields = ('url', 'owner', 'name', 'expired')
2012-10-21 18:34:07 +04:00
Would produce output similar to:
{
'url': 'http://example.com/api/accounts/3/',
'owner': 'http://example.com/api/users/12/',
'name': 'FooCorp business account',
'expired': True
}
2012-10-21 18:34:07 +04:00
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.
You can customize this behaviour by overriding the `.to_native(self, value)` method.
2012-10-05 20:02:33 +04:00
## WritableField
A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
2012-10-05 20:02:33 +04:00
## ModelField
2012-10-05 20:02:33 +04:00
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
**Signature:** `ModelField(model_field=<Django ModelField class>)`
2012-10-08 18:46:52 +04:00
---
# Typed Fields
2012-10-05 20:02:33 +04:00
These fields represent basic datatypes, and support both reading and writing values.
## BooleanField
2012-10-21 20:40:49 +04:00
A Boolean representation.
Corresponds to `django.db.models.fields.BooleanField`.
## CharField
2012-10-21 20:40:49 +04:00
A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`.
Corresponds to `django.db.models.fields.CharField`
or `django.db.models.fields.TextField`.
2012-10-21 20:40:49 +04:00
**Signature:** `CharField(max_length=None, min_length=None)`
## ChoiceField
A field that can accept a value out of a limited set of choices.
## EmailField
A text representation, validates the text to be a valid e-mail address.
2012-10-21 20:40:49 +04:00
Corresponds to `django.db.models.fields.EmailField`
## DateField
2012-10-21 20:40:49 +04:00
A date representation.
Corresponds to `django.db.models.fields.DateField`
## DateTimeField
2012-10-21 20:40:49 +04:00
A date and time representation.
Corresponds to `django.db.models.fields.DateTimeField`
## IntegerField
2012-10-21 20:40:49 +04:00
An integer representation.
Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`
## FloatField
2012-10-21 20:40:49 +04:00
A floating point representation.
Corresponds to `django.db.models.fields.FloatField`.
2012-10-08 18:46:52 +04:00
---
# Relational Fields
2012-10-05 20:02:33 +04:00
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`.
## 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 customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
## ManyRelatedField
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.
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',)
2012-10-21 18:34:07 +04:00
Then an example output format for a Bookmark instance would be:
{
'tags': [u'django', u'python'],
'url': u'https://www.djangoproject.com/'
}
## PrimaryKeyRelatedField / ManyPrimaryKeyRelatedField
`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
**Arguments**:
* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
## SlugRelatedField / ManySlugRelatedField
`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
**Arguments**:
* `slug_field` - The field on the target that should used as the representation. This should be a field that uniquely identifies any given instance. For example, `username`.
* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
2012-10-29 00:18:02 +04:00
## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
2012-10-29 00:18:02 +04:00
`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
2012-10-29 00:18:02 +04:00
**Arguments**:
2012-10-29 00:18:02 +04:00
* `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.
* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
2012-10-29 00:18:02 +04:00
2012-10-05 20:02:33 +04:00
## HyperLinkedIdentityField
2012-10-29 00:18:02 +04:00
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
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.
[cite]: http://www.python.org/dev/peps/pep-0020/