2008-08-24 06:25:40 +08:00
|
|
|
===========================
|
|
|
|
Writing custom model fields
|
|
|
|
===========================
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2009-12-17 02:13:34 +08:00
|
|
|
.. currentmodule:: django.db.models
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Introduction
|
|
|
|
============
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
The :doc:`model reference </topics/db/models>` documentation explains how to use
|
2008-08-24 06:25:40 +08:00
|
|
|
Django's standard field classes -- :class:`~django.db.models.CharField`,
|
|
|
|
:class:`~django.db.models.DateField`, etc. For many purposes, those classes are
|
|
|
|
all you'll need. Sometimes, though, the Django version won't meet your precise
|
|
|
|
requirements, or you'll want to use a field that is entirely different from
|
|
|
|
those shipped with Django.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Django's built-in field types don't cover every possible database column type --
|
|
|
|
only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
|
|
|
|
column types, such as geographic polygons or even user-created types such as
|
|
|
|
`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.
|
|
|
|
|
2013-03-17 18:45:45 +08:00
|
|
|
.. _PostgreSQL custom types: http://www.postgresql.org/docs/current/interactive/sql-createtype.html
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
Alternatively, you may have a complex Python object that can somehow be
|
|
|
|
serialized to fit into a standard database column type. This is another case
|
|
|
|
where a ``Field`` subclass will help you use your object with your models.
|
|
|
|
|
|
|
|
Our example object
|
|
|
|
------------------
|
|
|
|
|
|
|
|
Creating custom fields requires a bit of attention to detail. To make things
|
2008-12-03 13:50:11 +08:00
|
|
|
easier to follow, we'll use a consistent example throughout this document:
|
|
|
|
wrapping a Python object representing the deal of cards in a hand of Bridge_.
|
2013-06-27 01:25:34 +08:00
|
|
|
Don't worry, you don't have to know how to play Bridge to follow this example.
|
2008-12-03 13:50:11 +08:00
|
|
|
You only need to know that 52 cards are dealt out equally to four players, who
|
|
|
|
are traditionally called *north*, *east*, *south* and *west*. Our class looks
|
|
|
|
something like this::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
class Hand(object):
|
2009-12-13 23:16:48 +08:00
|
|
|
"""A hand of cards (bridge style)"""
|
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
def __init__(self, north, east, south, west):
|
|
|
|
# Input parameters are lists of cards ('Ah', '9s', etc)
|
|
|
|
self.north = north
|
|
|
|
self.east = east
|
|
|
|
self.south = south
|
|
|
|
self.west = west
|
Fixed #10389, #10501, #10502, #10540, #10562, #10563, #10564, #10565, #10568, #10569, #10614, #10617, #10619 -- Fixed several typos as well as a couple minor issues in the docs, patches from timo, nih, bthomas, rduffield, UloPe, and sebleier@gmail.com.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10242 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-03-31 15:01:01 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
# ... (other possibly useful methods omitted) ...
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
.. _Bridge: http://en.wikipedia.org/wiki/Contract_bridge
|
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
This is just an ordinary Python class, with nothing Django-specific about it.
|
2007-12-17 14:59:01 +08:00
|
|
|
We'd like to be able to do things like this in our models (we assume the
|
|
|
|
``hand`` attribute on the model is an instance of ``Hand``)::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
example = MyModel.objects.get(pk=1)
|
2012-04-29 00:02:01 +08:00
|
|
|
print(example.hand.north)
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
new_hand = Hand(north, east, south, west)
|
|
|
|
example.hand = new_hand
|
|
|
|
example.save()
|
|
|
|
|
|
|
|
We assign to and retrieve from the ``hand`` attribute in our model just like
|
|
|
|
any other Python class. The trick is to tell Django how to handle saving and
|
2007-11-15 17:21:36 +08:00
|
|
|
loading such an object.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
In order to use the ``Hand`` class in our models, we **do not** have to change
|
|
|
|
this class at all. This is ideal, because it means you can easily write
|
|
|
|
model support for existing classes where you cannot change the source code.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
You might only be wanting to take advantage of custom database column
|
|
|
|
types and deal with the data as standard Python types in your models;
|
|
|
|
strings, or floats, for example. This case is similar to our ``Hand``
|
|
|
|
example and we'll note any differences as we go along.
|
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
Background theory
|
2007-11-05 21:59:52 +08:00
|
|
|
=================
|
|
|
|
|
|
|
|
Database storage
|
|
|
|
----------------
|
|
|
|
|
|
|
|
The simplest way to think of a model field is that it provides a way to take a
|
|
|
|
normal Python object -- string, boolean, ``datetime``, or something more
|
|
|
|
complex like ``Hand`` -- and convert it to and from a format that is useful
|
|
|
|
when dealing with the database (and serialization, but, as we'll see later,
|
|
|
|
that falls out fairly naturally once you have the database side under control).
|
|
|
|
|
|
|
|
Fields in a model must somehow be converted to fit into an existing database
|
|
|
|
column type. Different databases provide different sets of valid column types,
|
|
|
|
but the rule is still the same: those are the only types you have to work
|
2007-12-02 01:29:45 +08:00
|
|
|
with. Anything you want to store in the database must fit into one of
|
2007-11-05 21:59:52 +08:00
|
|
|
those types.
|
|
|
|
|
|
|
|
Normally, you're either writing a Django field to match a particular database
|
|
|
|
column type, or there's a fairly straightforward way to convert your data to,
|
|
|
|
say, a string.
|
|
|
|
|
|
|
|
For our ``Hand`` example, we could convert the card data to a string of 104
|
2007-12-02 01:29:45 +08:00
|
|
|
characters by concatenating all the cards together in a pre-determined order --
|
|
|
|
say, all the *north* cards first, then the *east*, *south* and *west* cards. So
|
|
|
|
``Hand`` objects can be saved to text or character columns in the database.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
What does a field class do?
|
|
|
|
---------------------------
|
|
|
|
|
|
|
|
All of Django's fields (and when we say *fields* in this document, we always
|
2010-08-20 03:27:44 +08:00
|
|
|
mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
|
2008-08-24 06:25:40 +08:00
|
|
|
of :class:`django.db.models.Field`. Most of the information that Django records
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
about a field is common to all fields -- name, help text, uniqueness and so
|
|
|
|
forth. Storing all that information is handled by ``Field``. We'll get into the
|
|
|
|
precise details of what ``Field`` can do later on; for now, suffice it to say
|
|
|
|
that everything descends from ``Field`` and then customizes key pieces of the
|
|
|
|
class behavior.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
It's important to realize that a Django field class is not what is stored in
|
2007-11-05 21:59:52 +08:00
|
|
|
your model attributes. The model attributes contain normal Python objects. The
|
|
|
|
field classes you define in a model are actually stored in the ``Meta`` class
|
|
|
|
when the model class is created (the precise details of how this is done are
|
|
|
|
unimportant here). This is because the field classes aren't necessary when
|
|
|
|
you're just creating and modifying attributes. Instead, they provide the
|
|
|
|
machinery for converting between the attribute value and what is stored in the
|
2010-08-20 03:27:44 +08:00
|
|
|
database or sent to the :doc:`serializer </topics/serialization>`.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Keep this in mind when creating your own custom fields. The Django ``Field``
|
|
|
|
subclass you write provides the machinery for converting between your Python
|
|
|
|
instances and the database/serializer values in various ways (there are
|
|
|
|
differences between storing a value and using a value for lookups, for
|
2007-12-02 01:29:45 +08:00
|
|
|
example). If this sounds a bit tricky, don't worry -- it will become clearer in
|
|
|
|
the examples below. Just remember that you will often end up creating two
|
|
|
|
classes when you want a custom field:
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* The first class is the Python object that your users will manipulate.
|
|
|
|
They will assign it to the model attribute, they will read from it for
|
|
|
|
displaying purposes, things like that. This is the ``Hand`` class in our
|
|
|
|
example.
|
2007-12-02 01:29:45 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* The second class is the ``Field`` subclass. This is the class that knows
|
|
|
|
how to convert your first class back and forth between its permanent
|
|
|
|
storage form and the Python form.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Writing a field subclass
|
|
|
|
========================
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
When planning your :class:`~django.db.models.Field` subclass, first give some
|
|
|
|
thought to which existing :class:`~django.db.models.Field` class your new field
|
|
|
|
is most similar to. Can you subclass an existing Django field and save yourself
|
|
|
|
some work? If not, you should subclass the :class:`~django.db.models.Field`
|
|
|
|
class, from which everything is descended.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Initializing your new field is a matter of separating out any arguments that are
|
|
|
|
specific to your case from the common arguments and passing the latter to the
|
2012-12-29 23:35:12 +08:00
|
|
|
``__init__()`` method of :class:`~django.db.models.Field` (or your parent
|
|
|
|
class).
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
In our example, we'll call our field ``HandField``. (It's a good idea to call
|
2008-08-24 06:25:40 +08:00
|
|
|
your :class:`~django.db.models.Field` subclass ``<Something>Field``, so it's
|
|
|
|
easily identifiable as a :class:`~django.db.models.Field` subclass.) It doesn't
|
|
|
|
behave like any existing field, so we'll subclass directly from
|
|
|
|
:class:`~django.db.models.Field`::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class HandField(models.Field):
|
2009-12-17 02:13:34 +08:00
|
|
|
|
|
|
|
description = "A hand of cards (bridge style)"
|
2009-12-13 23:16:48 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['max_length'] = 104
|
|
|
|
super(HandField, self).__init__(*args, **kwargs)
|
|
|
|
|
2008-10-24 15:16:23 +08:00
|
|
|
Our ``HandField`` accepts most of the standard field options (see the list
|
2007-11-05 21:59:52 +08:00
|
|
|
below), but we ensure it has a fixed length, since it only needs to hold 52
|
|
|
|
card values plus their suits; 104 characters in total.
|
|
|
|
|
|
|
|
.. note::
|
2011-09-17 02:06:42 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
Many of Django's model fields accept options that they don't do anything
|
2008-08-24 06:25:40 +08:00
|
|
|
with. For example, you can pass both
|
|
|
|
:attr:`~django.db.models.Field.editable` and
|
2012-09-08 18:38:41 +08:00
|
|
|
:attr:`~django.db.models.DateField.auto_now` to a
|
2008-08-24 06:25:40 +08:00
|
|
|
:class:`django.db.models.DateField` and it will simply ignore the
|
|
|
|
:attr:`~django.db.models.Field.editable` parameter
|
2012-09-08 18:38:41 +08:00
|
|
|
(:attr:`~django.db.models.DateField.auto_now` being set implies
|
2008-08-24 06:25:40 +08:00
|
|
|
``editable=False``). No error is raised in this case.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
This behavior simplifies the field classes, because they don't need to
|
2007-11-05 21:59:52 +08:00
|
|
|
check for options that aren't necessary. They just pass all the options to
|
2007-12-02 01:29:45 +08:00
|
|
|
the parent class and then don't use them later on. It's up to you whether
|
2011-09-17 02:06:42 +08:00
|
|
|
you want your fields to be more strict about the options they select, or to
|
|
|
|
use the simpler, more permissive behavior of the current fields.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
The ``Field.__init__()`` method takes the following parameters:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* :attr:`~django.db.models.Field.verbose_name`
|
2013-01-01 21:12:42 +08:00
|
|
|
* ``name``
|
2011-10-14 08:12:01 +08:00
|
|
|
* :attr:`~django.db.models.Field.primary_key`
|
2013-01-01 21:12:42 +08:00
|
|
|
* :attr:`~django.db.models.CharField.max_length`
|
2011-10-14 08:12:01 +08:00
|
|
|
* :attr:`~django.db.models.Field.unique`
|
|
|
|
* :attr:`~django.db.models.Field.blank`
|
|
|
|
* :attr:`~django.db.models.Field.null`
|
|
|
|
* :attr:`~django.db.models.Field.db_index`
|
2013-01-01 21:12:42 +08:00
|
|
|
* ``rel``: Used for related fields (like :class:`ForeignKey`). For advanced
|
|
|
|
use only.
|
2011-10-14 08:12:01 +08:00
|
|
|
* :attr:`~django.db.models.Field.default`
|
|
|
|
* :attr:`~django.db.models.Field.editable`
|
2013-01-01 21:12:42 +08:00
|
|
|
* ``serialize``: If ``False``, the field will not be serialized when the model
|
|
|
|
is passed to Django's :doc:`serializers </topics/serialization>`. Defaults to
|
|
|
|
``True``.
|
2011-10-14 08:12:01 +08:00
|
|
|
* :attr:`~django.db.models.Field.unique_for_date`
|
|
|
|
* :attr:`~django.db.models.Field.unique_for_month`
|
|
|
|
* :attr:`~django.db.models.Field.unique_for_year`
|
|
|
|
* :attr:`~django.db.models.Field.choices`
|
|
|
|
* :attr:`~django.db.models.Field.help_text`
|
|
|
|
* :attr:`~django.db.models.Field.db_column`
|
2011-10-15 05:49:43 +08:00
|
|
|
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
|
|
|
|
backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
|
|
|
|
ignore this option.
|
2013-03-22 17:50:45 +08:00
|
|
|
* ``auto_created``: ``True`` if the field was automatically created, as for the
|
|
|
|
:class:`~django.db.models.OneToOneField` used by model inheritance. For
|
|
|
|
advanced use only.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
All of the options without an explanation in the above list have the same
|
2010-08-20 03:27:44 +08:00
|
|
|
meaning they do for normal Django fields. See the :doc:`field documentation
|
|
|
|
</ref/models/fields>` for examples and details.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-04-28 20:18:43 +08:00
|
|
|
.. _custom-field-deconstruct-method:
|
|
|
|
|
2013-11-27 23:20:53 +08:00
|
|
|
Field deconstruction
|
|
|
|
--------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
``deconstruct()`` is part of the migrations framework in Django 1.7 and
|
|
|
|
above. If you have custom fields from previous versions they will
|
|
|
|
need this method added before you can use them with migrations.
|
|
|
|
|
2014-04-28 20:18:43 +08:00
|
|
|
The counterpoint to writing your ``__init__()`` method is writing the
|
|
|
|
``deconstruct()`` method. This method tells Django how to take an instance
|
2013-11-27 23:20:53 +08:00
|
|
|
of your new field and reduce it to a serialized form - in particular, what
|
2014-04-28 20:18:43 +08:00
|
|
|
arguments to pass to ``__init__()`` to re-create it.
|
2013-11-27 23:20:53 +08:00
|
|
|
|
|
|
|
If you haven't added any extra options on top of the field you inherited from,
|
2014-04-28 20:18:43 +08:00
|
|
|
then there's no need to write a new ``deconstruct()`` method. If, however,
|
|
|
|
you're, changing the arguments passed in ``__init__()`` (like we are in
|
|
|
|
``HandField``), you'll need to supplement the values being passed.
|
2013-11-27 23:20:53 +08:00
|
|
|
|
2014-04-28 20:18:43 +08:00
|
|
|
The contract of ``deconstruct()`` is simple; it returns a tuple of four items:
|
2013-11-27 23:20:53 +08:00
|
|
|
the field's attribute name, the full import path of the field class, the
|
2014-04-28 20:18:43 +08:00
|
|
|
positional arguments (as a list), and the keyword arguments (as a dict). Note
|
|
|
|
this is different from the ``deconstruct()`` method :ref:`for custom classes
|
|
|
|
<custom-deconstruct-method>` which returns a tuple of three things.
|
2013-11-27 23:20:53 +08:00
|
|
|
|
|
|
|
As a custom field author, you don't need to care about the first two values;
|
|
|
|
the base ``Field`` class has all the code to work out the field's attribute
|
|
|
|
name and import path. You do, however, have to care about the positional
|
|
|
|
and keyword arguments, as these are likely the things you are changing.
|
|
|
|
|
|
|
|
For example, in our ``HandField`` class we're always forcibly setting
|
2014-04-28 20:18:43 +08:00
|
|
|
max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``
|
2013-11-27 23:20:53 +08:00
|
|
|
class will see this and try to return it in the keyword arguments; thus,
|
|
|
|
we can drop it from the keyword arguments for readability::
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['max_length'] = 104
|
|
|
|
super(HandField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super(HandField, self).deconstruct()
|
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
|
|
If you add a new keyword argument, you need to write code to put its value
|
|
|
|
into ``kwargs`` yourself::
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class CommaSepField(models.Field):
|
|
|
|
"Implements comma-separated storage of lists"
|
|
|
|
|
|
|
|
def __init__(self, separator=",", *args, **kwargs):
|
2014-05-04 07:18:13 +08:00
|
|
|
self.separator = separator
|
2013-11-27 23:20:53 +08:00
|
|
|
super(CommaSepField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super(CommaSepField, self).deconstruct()
|
|
|
|
# Only include kwarg if it's not the default
|
|
|
|
if self.separator != ",":
|
|
|
|
kwargs['separator'] = self.separator
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
|
|
More complex examples are beyond the scope of this document, but remember -
|
2014-04-28 20:18:43 +08:00
|
|
|
for any configuration of your Field instance, ``deconstruct()`` must return
|
2013-11-27 23:20:53 +08:00
|
|
|
arguments that you can pass to ``__init__`` to reconstruct that state.
|
|
|
|
|
|
|
|
Pay extra attention if you set new default values for arguments in the
|
|
|
|
``Field`` superclass; you want to make sure they're always included, rather
|
|
|
|
than disappearing if they take on the old default value.
|
|
|
|
|
|
|
|
In addition, try to avoid returning values as positional arguments; where
|
2013-12-06 06:11:30 +08:00
|
|
|
possible, return values as keyword arguments for maximum future compatibility.
|
2013-11-27 23:20:53 +08:00
|
|
|
Of course, if you change the names of things more often than their position
|
|
|
|
in the constructor's argument list, you might prefer positional, but bear in
|
|
|
|
mind that people will be reconstructing your field from the serialized version
|
|
|
|
for quite a while (possibly years), depending how long your migrations live for.
|
|
|
|
|
|
|
|
You can see the results of deconstruction by looking in migrations that include
|
|
|
|
the field, and you can test deconstruction in unit tests by just deconstructing
|
|
|
|
and reconstructing the field::
|
|
|
|
|
|
|
|
name, path, args, kwargs = my_field_instance.deconstruct()
|
|
|
|
new_instance = MyField(*args, **kwargs)
|
|
|
|
self.assertEqual(my_field_instance.some_attribute, new_instance.some_attribute)
|
|
|
|
|
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
The ``SubfieldBase`` metaclass
|
|
|
|
------------------------------
|
|
|
|
|
2011-02-16 08:24:49 +08:00
|
|
|
.. class:: django.db.models.SubfieldBase
|
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
As we indicated in the introduction_, field subclasses are often needed for
|
2007-12-02 01:29:45 +08:00
|
|
|
two reasons: either to take advantage of a custom database column type, or to
|
|
|
|
handle complex Python types. Obviously, a combination of the two is also
|
|
|
|
possible. If you're only working with custom database column types and your
|
2007-11-05 21:59:52 +08:00
|
|
|
model fields appear in Python as standard Python types direct from the
|
|
|
|
database backend, you don't need to worry about this section.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
If you're handling custom Python types, such as our ``Hand`` class, we need to
|
|
|
|
make sure that when Django initializes an instance of our model and assigns a
|
|
|
|
database value to our custom field attribute, we convert that value into the
|
2007-11-05 21:59:52 +08:00
|
|
|
appropriate Python object. The details of how this happens internally are a
|
2007-12-02 01:29:45 +08:00
|
|
|
little complex, but the code you need to write in your ``Field`` class is
|
2008-08-24 06:25:40 +08:00
|
|
|
simple: make sure your field subclass uses a special metaclass:
|
|
|
|
|
2013-07-05 18:53:19 +08:00
|
|
|
For example, on Python 2::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2007-11-15 17:21:36 +08:00
|
|
|
class HandField(models.Field):
|
2009-12-17 02:13:34 +08:00
|
|
|
|
|
|
|
description = "A hand of cards (bridge style)"
|
2009-12-13 23:16:48 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
__metaclass__ = models.SubfieldBase
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2013-07-05 18:53:19 +08:00
|
|
|
...
|
|
|
|
|
|
|
|
On Python 3, in lieu of setting the ``__metaclass__`` attribute, add
|
|
|
|
``metaclass`` to the class definition::
|
|
|
|
|
|
|
|
class HandField(models.Field, metaclass=models.SubfieldBase):
|
|
|
|
...
|
|
|
|
|
|
|
|
If you want your code to work on Python 2 & 3, you can use
|
|
|
|
:func:`six.with_metaclass`::
|
|
|
|
|
|
|
|
from django.utils.six import with_metaclass
|
|
|
|
|
|
|
|
class HandField(with_metaclass(models.SubfieldBase, models.Field)):
|
|
|
|
...
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2011-02-16 08:24:49 +08:00
|
|
|
This ensures that the :meth:`.to_python` method, documented below, will always
|
|
|
|
be called when the attribute is initialized.
|
2007-12-02 01:29:45 +08:00
|
|
|
|
2010-04-15 22:34:40 +08:00
|
|
|
ModelForms and custom fields
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2011-02-16 08:24:49 +08:00
|
|
|
If you use :class:`~django.db.models.SubfieldBase`, :meth:`.to_python`
|
2010-04-15 22:34:40 +08:00
|
|
|
will be called every time an instance of the field is assigned a
|
|
|
|
value. This means that whenever a value may be assigned to the field,
|
|
|
|
you need to ensure that it will be of the correct datatype, or that
|
|
|
|
you handle any exceptions.
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
This is especially important if you use :doc:`ModelForms
|
|
|
|
</topics/forms/modelforms>`. When saving a ModelForm, Django will use
|
2010-04-15 22:34:40 +08:00
|
|
|
form values to instantiate model instances. However, if the cleaned
|
|
|
|
form data can't be used as valid input to the field, the normal form
|
|
|
|
validation process will break.
|
|
|
|
|
|
|
|
Therefore, you must ensure that the form field used to represent your
|
|
|
|
custom field performs whatever input validation and data cleaning is
|
|
|
|
necessary to convert user-provided form input into a
|
2013-08-15 19:14:10 +08:00
|
|
|
``to_python()``-compatible model field value. This may require writing a
|
2011-02-16 08:24:49 +08:00
|
|
|
custom form field, and/or implementing the :meth:`.formfield` method on
|
2013-08-15 19:14:10 +08:00
|
|
|
your field to return a form field class whose ``to_python()`` returns the
|
2010-04-15 22:34:40 +08:00
|
|
|
correct datatype.
|
2009-12-13 23:16:48 +08:00
|
|
|
|
2011-01-03 21:29:17 +08:00
|
|
|
Documenting your custom field
|
2009-12-13 23:16:48 +08:00
|
|
|
-----------------------------
|
|
|
|
|
|
|
|
As always, you should document your field type, so users will know what it is.
|
2009-12-17 02:13:34 +08:00
|
|
|
In addition to providing a docstring for it, which is useful for developers,
|
|
|
|
you can also allow users of the admin app to see a short description of the
|
2010-11-07 17:21:55 +08:00
|
|
|
field type via the :doc:`django.contrib.admindocs
|
|
|
|
</ref/contrib/admin/admindocs>` application. To do this simply provide
|
2014-06-23 14:33:42 +08:00
|
|
|
descriptive text in a :attr:`~Field.description` class attribute of your custom
|
|
|
|
field. In the above example, the description displayed by the ``admindocs``
|
2010-11-07 17:21:55 +08:00
|
|
|
application for a ``HandField`` will be 'A hand of cards (bridge style)'.
|
2009-12-13 23:16:48 +08:00
|
|
|
|
2013-07-07 06:31:59 +08:00
|
|
|
In the :mod:`django.contrib.admindocs` display, the field description is
|
|
|
|
interpolated with ``field.__dict__`` which allows the description to
|
|
|
|
incorporate arguments of the field. For example, the description for
|
|
|
|
:class:`~django.db.models.CharField` is::
|
|
|
|
|
|
|
|
description = _("String (up to %(max_length)s)")
|
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
Useful methods
|
|
|
|
--------------
|
|
|
|
|
Fixed #10389, #10501, #10502, #10540, #10562, #10563, #10564, #10565, #10568, #10569, #10614, #10617, #10619 -- Fixed several typos as well as a couple minor issues in the docs, patches from timo, nih, bthomas, rduffield, UloPe, and sebleier@gmail.com.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10242 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-03-31 15:01:01 +08:00
|
|
|
Once you've created your :class:`~django.db.models.Field` subclass and set up
|
2008-08-24 06:25:40 +08:00
|
|
|
the ``__metaclass__``, you might consider overriding a few standard methods,
|
2007-12-02 01:29:45 +08:00
|
|
|
depending on your field's behavior. The list of methods below is in
|
|
|
|
approximately decreasing order of importance, so start from the top.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _custom-database-types:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Custom database types
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
Say you've created a PostgreSQL custom type called ``mytype``. You can
|
|
|
|
subclass ``Field`` and implement the :meth:`~Field.db_type` method, like so::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class MytypeField(models.Field):
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
2007-11-05 21:59:52 +08:00
|
|
|
return 'mytype'
|
|
|
|
|
|
|
|
Once you have ``MytypeField``, you can use it in any model, just like any other
|
|
|
|
``Field`` type::
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
name = models.CharField(max_length=80)
|
|
|
|
something_else = MytypeField()
|
|
|
|
|
|
|
|
If you aim to build a database-agnostic application, you should account for
|
|
|
|
differences in database column types. For example, the date/time column type
|
|
|
|
in PostgreSQL is called ``timestamp``, while the same column in MySQL is called
|
2014-06-23 14:33:42 +08:00
|
|
|
``datetime``. The simplest way to handle this in a :meth:`~Field.db_type`
|
2011-02-16 08:24:49 +08:00
|
|
|
method is to check the ``connection.settings_dict['ENGINE']`` attribute.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
For example::
|
|
|
|
|
|
|
|
class MyDateField(models.Field):
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
|
|
|
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
|
2007-11-05 21:59:52 +08:00
|
|
|
return 'datetime'
|
|
|
|
else:
|
|
|
|
return 'timestamp'
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
The :meth:`~Field.db_type` method is called by Django when the framework
|
2011-02-16 08:24:49 +08:00
|
|
|
constructs the ``CREATE TABLE`` statements for your application -- that is,
|
2014-04-28 20:18:43 +08:00
|
|
|
when you first create your tables. It is also called when constructing a
|
2013-12-19 05:31:48 +08:00
|
|
|
``WHERE`` clause that includes the model field -- that is, when you retrieve data
|
|
|
|
using QuerySet methods like ``get()``, ``filter()``, and ``exclude()`` and have
|
|
|
|
the model field as an argument. It's not called at any other time, so it can afford to
|
|
|
|
execute slightly complex code, such as the ``connection.settings_dict`` check in
|
|
|
|
the above example.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Some database column types accept parameters, such as ``CHAR(25)``, where the
|
|
|
|
parameter ``25`` represents the maximum column length. In cases like these,
|
|
|
|
it's more flexible if the parameter is specified in the model rather than being
|
|
|
|
hard-coded in the ``db_type()`` method. For example, it wouldn't make much
|
|
|
|
sense to have a ``CharMaxlength25Field``, shown here::
|
|
|
|
|
|
|
|
# This is a silly example of hard-coded parameters.
|
|
|
|
class CharMaxlength25Field(models.Field):
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
2007-11-05 21:59:52 +08:00
|
|
|
return 'char(25)'
|
|
|
|
|
|
|
|
# In the model:
|
|
|
|
class MyModel(models.Model):
|
|
|
|
# ...
|
|
|
|
my_field = CharMaxlength25Field()
|
|
|
|
|
|
|
|
The better way of doing this would be to make the parameter specifiable at run
|
|
|
|
time -- i.e., when the class is instantiated. To do that, just implement
|
2014-06-23 14:33:42 +08:00
|
|
|
``Field.__init__()``, like so::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
# This is a much more flexible example.
|
|
|
|
class BetterCharField(models.Field):
|
|
|
|
def __init__(self, max_length, *args, **kwargs):
|
|
|
|
self.max_length = max_length
|
|
|
|
super(BetterCharField, self).__init__(*args, **kwargs)
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
2007-11-05 21:59:52 +08:00
|
|
|
return 'char(%s)' % self.max_length
|
|
|
|
|
|
|
|
# In the model:
|
|
|
|
class MyModel(models.Model):
|
|
|
|
# ...
|
|
|
|
my_field = BetterCharField(25)
|
|
|
|
|
|
|
|
Finally, if your column requires truly complex SQL setup, return ``None`` from
|
2011-02-16 08:24:49 +08:00
|
|
|
:meth:`.db_type`. This will cause Django's SQL creation code to skip
|
|
|
|
over this field. You are then responsible for creating the column in the right
|
|
|
|
table in some other way, of course, but this gives you a way to tell Django to
|
|
|
|
get out of the way.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _converting-database-values-to-python-objects:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Converting database values to Python objects
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
If your custom :class:`~Field` class deals with data structures that are more
|
|
|
|
complex than strings, dates, integers or floats, then you'll need to override
|
|
|
|
:meth:`~Field.to_python`. As a general rule, the method should deal gracefully
|
2008-08-24 06:25:40 +08:00
|
|
|
with any of the following arguments:
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* An instance of the correct type (e.g., ``Hand`` in our ongoing example).
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* A string (e.g., from a deserializer).
|
2007-12-02 01:29:45 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Whatever the database returns for the column type you're using.
|
2007-12-02 01:29:45 +08:00
|
|
|
|
|
|
|
In our ``HandField`` class, we're storing the data as a VARCHAR field in the
|
|
|
|
database, so we need to be able to process strings and ``Hand`` instances in
|
2011-02-16 08:24:49 +08:00
|
|
|
:meth:`.to_python`::
|
2007-12-02 01:29:45 +08:00
|
|
|
|
|
|
|
import re
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if isinstance(value, Hand):
|
|
|
|
return value
|
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
# The string case.
|
2007-11-05 21:59:52 +08:00
|
|
|
p1 = re.compile('.{26}')
|
|
|
|
p2 = re.compile('..')
|
|
|
|
args = [p2.findall(x) for x in p1.findall(value)]
|
2012-06-30 20:30:32 +08:00
|
|
|
if len(args) != 4:
|
|
|
|
raise ValidationError("Invalid input for a Hand instance")
|
2007-11-05 21:59:52 +08:00
|
|
|
return Hand(*args)
|
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
Notice that we always return a ``Hand`` instance from this method. That's the
|
2012-06-30 20:30:32 +08:00
|
|
|
Python object type we want to store in the model's attribute. If anything is
|
2012-07-02 16:16:42 +08:00
|
|
|
going wrong during value conversion, you should raise a
|
2012-06-30 20:30:32 +08:00
|
|
|
:exc:`~django.core.exceptions.ValidationError` exception.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
**Remember:** If your custom field needs the :meth:`~Field.to_python` method to be
|
2007-12-09 16:10:09 +08:00
|
|
|
called when it is created, you should be using `The SubfieldBase metaclass`_
|
2014-06-23 14:33:42 +08:00
|
|
|
mentioned earlier. Otherwise :meth:`~Field.to_python` won't be called
|
2011-02-16 08:24:49 +08:00
|
|
|
automatically.
|
2007-12-09 16:10:09 +08:00
|
|
|
|
2012-10-19 18:52:30 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
If your custom field allows ``null=True``, any field method that takes
|
|
|
|
``value`` as an argument, like :meth:`~Field.to_python` and
|
|
|
|
:meth:`~Field.get_prep_value`, should handle the case when ``value`` is
|
|
|
|
``None``.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _converting-python-objects-to-query-values:
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
Converting Python objects to query values
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
Since using a database requires conversion in both ways, if you override
|
|
|
|
:meth:`~Field.to_python` you also have to override :meth:`~Field.get_prep_value`
|
|
|
|
to convert Python objects back to query values.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2008-03-19 03:13:41 +08:00
|
|
|
return ''.join([''.join(l) for l in (value.north,
|
|
|
|
value.east, value.south, value.west)])
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-04-21 04:25:39 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
If your custom field uses the ``CHAR``, ``VARCHAR`` or ``TEXT``
|
|
|
|
types for MySQL, you must make sure that :meth:`.get_prep_value`
|
|
|
|
always returns a string type. MySQL performs flexible and unexpected
|
|
|
|
matching when a query is performed on these types and the provided
|
|
|
|
value is an integer, which can cause queries to include unexpected
|
|
|
|
objects in their results. This problem cannot occur if you always
|
|
|
|
return a string type from :meth:`.get_prep_value`.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _converting-query-values-to-database-values:
|
2014-04-21 04:25:39 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
Converting query values to database values
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Some data types (for example, dates) need to be in a specific format
|
|
|
|
before they can be used by a database backend.
|
2014-06-23 14:33:42 +08:00
|
|
|
:meth:`~Field.get_db_prep_value` is the method where those conversions should
|
2009-12-22 23:18:51 +08:00
|
|
|
be made. The specific connection that will be used for the query is
|
|
|
|
passed as the ``connection`` parameter. This allows you to use
|
|
|
|
backend-specific conversion logic if it is required.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
For example, Django uses the following method for its
|
|
|
|
:class:``~models.BinaryField``::
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
value = super(BinaryField, self).get_db_prep_value(value, connection, prepared)
|
|
|
|
if value is not None:
|
|
|
|
return connection.Database.Binary(value)
|
|
|
|
return value
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
In case your custom field needs a special conversion when being saved that is
|
|
|
|
not the same as the conversion used for normal query parameters, you can
|
|
|
|
override :meth:`~Field.get_db_prep_save`.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _preprocessing-values-before-saving:
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Preprocessing values before saving
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
If you want to preprocess the value just before saving, you can use
|
|
|
|
:meth:`~Field.pre_save`. For example, Django's
|
2008-11-02 03:20:00 +08:00
|
|
|
:class:`~django.db.models.DateTimeField` uses this method to set the attribute
|
2012-09-08 18:38:41 +08:00
|
|
|
correctly in the case of :attr:`~django.db.models.DateField.auto_now` or
|
|
|
|
:attr:`~django.db.models.DateField.auto_now_add`.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
If you do override this method, you must return the value of the attribute at
|
|
|
|
the end. You should also update the model's attribute if you make any changes
|
|
|
|
to the value so that code holding references to the model will always see the
|
|
|
|
correct value.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _preparing-values-for-use-in-database-lookups:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Preparing values for use in database lookups
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
As with value conversions, preparing a value for database lookups is a
|
|
|
|
two phase process.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
:meth:`.get_prep_lookup` performs the first phase of lookup preparation:
|
|
|
|
type conversion and data validation.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Prepares the ``value`` for passing to the database when used in a lookup (a
|
2014-06-23 14:33:42 +08:00
|
|
|
``WHERE`` constraint in SQL). The ``lookup_type`` parameter will be one of the
|
|
|
|
valid Django filter lookups: ``exact``, ``iexact``, ``contains``, ``icontains``,
|
2007-11-05 21:59:52 +08:00
|
|
|
``gt``, ``gte``, ``lt``, ``lte``, ``in``, ``startswith``, ``istartswith``,
|
|
|
|
``endswith``, ``iendswith``, ``range``, ``year``, ``month``, ``day``,
|
|
|
|
``isnull``, ``search``, ``regex``, and ``iregex``.
|
|
|
|
|
2014-01-18 17:09:43 +08:00
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
2014-06-11 23:09:10 +08:00
|
|
|
If you are using :doc:`Custom lookups </howto/custom-lookups>` the
|
2014-01-18 17:09:43 +08:00
|
|
|
``lookup_type`` can be any ``lookup_name`` used by the project's custom
|
|
|
|
lookups.
|
|
|
|
|
2007-11-05 21:59:52 +08:00
|
|
|
Your method must be prepared to handle all of these ``lookup_type`` values and
|
|
|
|
should raise either a ``ValueError`` if the ``value`` is of the wrong sort (a
|
|
|
|
list when you were expecting an object, for example) or a ``TypeError`` if
|
|
|
|
your field does not support that type of lookup. For many fields, you can get
|
|
|
|
by with handling the lookup types that need special handling for your field
|
2014-06-23 14:33:42 +08:00
|
|
|
and pass the rest to the :meth:`~Field.get_db_prep_lookup` method of the parent
|
|
|
|
class.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
If you needed to implement :meth:`.get_db_prep_save`, you will usually need to
|
|
|
|
implement :meth:`.get_prep_lookup`. If you don't, :meth:`.get_prep_value` will
|
|
|
|
be called by the default implementation, to manage ``exact``, ``gt``, ``gte``,
|
2008-07-29 13:09:29 +08:00
|
|
|
``lt``, ``lte``, ``in`` and ``range`` lookups.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
You may also want to implement this method to limit the lookup types that could
|
|
|
|
be used with your custom field type.
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
Note that, for ``"range"`` and ``"in"`` lookups, ``get_prep_lookup`` will receive
|
2008-07-29 13:09:29 +08:00
|
|
|
a list of objects (presumably of the right type) and will need to convert them
|
|
|
|
to a list of things of the right type for passing to the database. Most of the
|
2009-12-22 23:18:51 +08:00
|
|
|
time, you can reuse ``get_prep_value()``, or at least factor out some common
|
2008-07-29 13:09:29 +08:00
|
|
|
pieces.
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
For example, the following code implements ``get_prep_lookup`` to limit the
|
2008-07-29 13:09:29 +08:00
|
|
|
accepted lookup types to ``exact`` and ``in``::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2007-11-05 21:59:52 +08:00
|
|
|
# We only handle 'exact' and 'in'. All others are errors.
|
|
|
|
if lookup_type == 'exact':
|
2010-05-10 21:17:12 +08:00
|
|
|
return self.get_prep_value(value)
|
2007-11-05 21:59:52 +08:00
|
|
|
elif lookup_type == 'in':
|
2009-12-22 23:18:51 +08:00
|
|
|
return [self.get_prep_value(v) for v in value]
|
2007-11-05 21:59:52 +08:00
|
|
|
else:
|
|
|
|
raise TypeError('Lookup type %r not supported.' % lookup_type)
|
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
For performing database-specific data conversions required by a lookup,
|
|
|
|
you can override :meth:`~Field.get_db_prep_lookup`.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _specifying-form-field-for-model-field:
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Specifying the form field for a model field
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
To customize the form field used by :class:`~django.forms.ModelForm`, you can
|
|
|
|
override :meth:`~Field.formfield`.
|
2013-08-30 11:44:37 +08:00
|
|
|
|
|
|
|
The form field class can be specified via the ``form_class`` and
|
|
|
|
``choices_form_class`` arguments; the latter is used if the field has choices
|
|
|
|
specified, the former otherwise. If these arguments are not provided,
|
|
|
|
:class:`~django.forms.CharField` or :class:`~django.forms.TypedChoiceField`
|
|
|
|
will be used.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
All of the ``kwargs`` dictionary is passed directly to the form field's
|
2012-12-29 23:35:12 +08:00
|
|
|
``__init__()`` method. Normally, all you need to do is set up a good default
|
2013-08-30 11:44:37 +08:00
|
|
|
for the ``form_class`` (and maybe ``choices_form_class``) argument and then
|
|
|
|
delegate further handling to the parent class. This might require you to write
|
|
|
|
a custom form field (and even a form widget). See the :doc:`forms documentation
|
|
|
|
</topics/forms/index>` for information about this.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
|
|
|
|
as::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
# This is a fairly standard way to set up some defaults
|
2007-12-02 01:29:45 +08:00
|
|
|
# while letting the caller override them.
|
2007-11-05 21:59:52 +08:00
|
|
|
defaults = {'form_class': MyFormField}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(HandField, self).formfield(**defaults)
|
|
|
|
|
Fixed #10389, #10501, #10502, #10540, #10562, #10563, #10564, #10565, #10568, #10569, #10614, #10617, #10619 -- Fixed several typos as well as a couple minor issues in the docs, patches from timo, nih, bthomas, rduffield, UloPe, and sebleier@gmail.com.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10242 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-03-31 15:01:01 +08:00
|
|
|
This assumes we've imported a ``MyFormField`` field class (which has its own
|
2007-12-02 01:29:45 +08:00
|
|
|
default widget). This document doesn't cover the details of writing custom form
|
|
|
|
fields.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2008-07-22 00:38:54 +08:00
|
|
|
.. _helper functions: ../forms/#generating-forms-for-models
|
|
|
|
.. _forms documentation: ../forms/
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
.. _emulating-built-in-field-types:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Emulating built-in field types
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2011-02-16 08:24:49 +08:00
|
|
|
If you have created a :meth:`.db_type` method, you don't need to worry about
|
|
|
|
:meth:`.get_internal_type` -- it won't be used much. Sometimes, though, your
|
2007-11-05 21:59:52 +08:00
|
|
|
database storage is similar in type to some other field, so you can use that
|
|
|
|
other field's logic to create the right column.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return 'CharField'
|
|
|
|
|
2013-11-21 22:04:31 +08:00
|
|
|
No matter which database backend we are using, this will mean that
|
|
|
|
:djadmin:`migrate` and other SQL commands create the right column type for
|
|
|
|
storing a string.
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2011-02-16 08:24:49 +08:00
|
|
|
If :meth:`.get_internal_type` returns a string that is not known to Django for
|
2007-11-05 21:59:52 +08:00
|
|
|
the database backend you are using -- that is, it doesn't appear in
|
2014-07-06 02:28:30 +08:00
|
|
|
``django.db.backends.<db_name>.creation.data_types`` -- the string will still be
|
2014-06-23 14:33:42 +08:00
|
|
|
used by the serializer, but the default :meth:`~Field.db_type` method will
|
|
|
|
return ``None``. See the documentation of :meth:`~Field.db_type` for reasons why
|
|
|
|
this might be useful. Putting a descriptive string in as the type of the field
|
|
|
|
for the serializer is a useful idea if you're ever going to be using the
|
|
|
|
serializer output in some other place, outside of Django.
|
|
|
|
|
|
|
|
.. _converting-model-field-to-serialization:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Converting field data for serialization
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2007-11-05 21:59:52 +08:00
|
|
|
|
2014-06-23 14:33:42 +08:00
|
|
|
To customize how the values are serialized by a serializer, you can override
|
|
|
|
:meth:`~Field.value_to_string`. Calling ``Field._get_val_from_obj(obj)`` is the
|
|
|
|
best way to get the value serialized. For example, since our ``HandField`` uses
|
|
|
|
strings for its data storage anyway, we can reuse some existing conversion code::
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
class HandField(models.Field):
|
|
|
|
# ...
|
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2007-11-05 21:59:52 +08:00
|
|
|
value = self._get_val_from_obj(obj)
|
2012-06-29 21:08:30 +08:00
|
|
|
return self.get_prep_value(value)
|
2007-11-05 21:59:52 +08:00
|
|
|
|
|
|
|
Some general advice
|
|
|
|
--------------------
|
|
|
|
|
2007-12-02 01:29:45 +08:00
|
|
|
Writing a custom field can be a tricky process, particularly if you're doing
|
|
|
|
complex conversions between your Python types and your database and
|
|
|
|
serialization formats. Here are a couple of tips to make things go more
|
|
|
|
smoothly:
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
1. Look at the existing Django fields (in
|
|
|
|
:file:`django/db/models/fields/__init__.py`) for inspiration. Try to find
|
|
|
|
a field that's similar to what you want and extend it a little bit,
|
|
|
|
instead of creating an entirely new field from scratch.
|
2007-12-02 01:29:45 +08:00
|
|
|
|
2014-02-09 19:38:13 +08:00
|
|
|
2. Put a ``__str__()`` (``__unicode__()`` on Python 2) method on the class you're
|
2011-10-14 08:12:01 +08:00
|
|
|
wrapping up as a field. There are a lot of places where the default
|
|
|
|
behavior of the field code is to call
|
2012-07-21 16:00:10 +08:00
|
|
|
:func:`~django.utils.encoding.force_text` on the value. (In our
|
2011-10-14 08:12:01 +08:00
|
|
|
examples in this document, ``value`` would be a ``Hand`` instance, not a
|
2014-02-09 19:38:13 +08:00
|
|
|
``HandField``). So if your ``__str__()`` method (``__unicode__()`` on
|
|
|
|
Python 2) automatically converts to the string form of your Python object,
|
2013-07-04 21:19:33 +08:00
|
|
|
you can save yourself a lot of work.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2008-08-09 04:59:02 +08:00
|
|
|
Writing a ``FileField`` subclass
|
2014-06-23 14:33:42 +08:00
|
|
|
================================
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
In addition to the above methods, fields that deal with files have a few other
|
|
|
|
special requirements which must be taken into account. The majority of the
|
|
|
|
mechanics provided by ``FileField``, such as controlling database storage and
|
|
|
|
retrieval, can remain unchanged, leaving subclasses to deal with the challenge
|
|
|
|
of supporting a particular type of file.
|
|
|
|
|
|
|
|
Django provides a ``File`` class, which is used as a proxy to the file's
|
2008-08-24 06:25:40 +08:00
|
|
|
contents and operations. This can be subclassed to customize how the file is
|
2008-08-09 04:59:02 +08:00
|
|
|
accessed, and what methods are available. It lives at
|
|
|
|
``django.db.models.fields.files``, and its default behavior is explained in the
|
2010-08-20 03:27:44 +08:00
|
|
|
:doc:`file documentation </ref/files/file>`.
|
2008-08-09 04:59:02 +08:00
|
|
|
|
|
|
|
Once a subclass of ``File`` is created, the new ``FileField`` subclass must be
|
|
|
|
told to use it. To do so, simply assign the new ``File`` subclass to the special
|
|
|
|
``attr_class`` attribute of the ``FileField`` subclass.
|
|
|
|
|
|
|
|
A few suggestions
|
|
|
|
------------------
|
|
|
|
|
|
|
|
In addition to the above details, there are a few guidelines which can greatly
|
|
|
|
improve the efficiency and readability of the field's code.
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
1. The source for Django's own ``ImageField`` (in
|
|
|
|
``django/db/models/fields/files.py``) is a great example of how to
|
|
|
|
subclass ``FileField`` to support a particular type of file, as it
|
|
|
|
incorporates all of the techniques described above.
|
|
|
|
|
|
|
|
2. Cache file attributes wherever possible. Since files may be stored in
|
|
|
|
remote storage systems, retrieving them may cost extra time, or even
|
|
|
|
money, that isn't always necessary. Once a file is retrieved to obtain
|
|
|
|
some data about its content, cache as much of that data as possible to
|
|
|
|
reduce the number of times the file must be retrieved on subsequent
|
|
|
|
calls for that information.
|