252
261
This ensures that the :meth:`to_python` method, documented below, will always be
253
262
called when the attribute is initialized.
264
ModelForms and custom fields
265
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267
If you use :class:`~django.db.models.SubfieldBase`, :meth:`to_python`
268
will be called every time an instance of the field is assigned a
269
value. This means that whenever a value may be assigned to the field,
270
you need to ensure that it will be of the correct datatype, or that
271
you handle any exceptions.
273
This is especially important if you use :ref:`ModelForms
274
<topics-forms-modelforms>`. When saving a ModelForm, Django will use
275
form values to instantiate model instances. However, if the cleaned
276
form data can't be used as valid input to the field, the normal form
277
validation process will break.
279
Therefore, you must ensure that the form field used to represent your
280
custom field performs whatever input validation and data cleaning is
281
necessary to convert user-provided form input into a
282
`to_python()`-compatible model field value. This may require writing a
283
custom form field, and/or implementing the :meth:`formfield` method on
284
your field to return a form field class whose `to_python()` returns the
287
Documenting your Custom Field
288
-----------------------------
290
.. class:: django.db.models.Field
292
.. attribute:: description
294
As always, you should document your field type, so users will know what it is.
295
In addition to providing a docstring for it, which is useful for developers,
296
you can also allow users of the admin app to see a short description of the
297
field type via the ``django.contrib.admindocs`` application. To do this simply
298
provide descriptive text in a ``description`` class attribute of your custom field.
299
In the above example, the type description displayed by the ``admindocs`` application
300
for a ``HandField`` will be 'A hand of cards (bridge style)'.
290
340
differences in database column types. For example, the date/time column type
291
341
in PostgreSQL is called ``timestamp``, while the same column in MySQL is called
292
342
``datetime``. The simplest way to handle this in a ``db_type()`` method is to
293
import the Django settings module and check the :setting:`DATABASE_ENGINE` setting.
343
check the ``connection.settings_dict['ENGINE']`` attribute.
296
347
class MyDateField(models.Field):
298
from django.conf import settings
299
if settings.DATABASE_ENGINE == 'mysql':
348
def db_type(self, connection):
349
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
300
350
return 'datetime'
302
352
return 'timestamp'
396
446
called when it is created, you should be using `The SubfieldBase metaclass`_
397
447
mentioned earlier. Otherwise :meth:`to_python` won't be called automatically.
399
Converting Python objects to database values
400
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402
.. method:: get_db_prep_value(self, value)
404
This is the reverse of :meth:`to_python` when working with the database backends
405
(as opposed to serialization). The ``value`` parameter is the current value of
406
the model's attribute (a field has no reference to its containing model, so it
407
cannot retrieve the value itself), and the method should return data in a format
408
that can be used as a parameter in a query for the database backend.
449
Converting Python objects to query values
450
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452
.. method:: get_prep_value(self, value)
454
.. versionadded:: 1.2
455
This method was factored out of ``get_db_prep_value()``
457
This is the reverse of :meth:`to_python` when working with the
458
database backends (as opposed to serialization). The ``value``
459
parameter is the current value of the model's attribute (a field has
460
no reference to its containing model, so it cannot retrieve the value
461
itself), and the method should return data in a format that has been
462
prepared for use as a parameter in a query.
464
This conversion should *not* include any database-specific
465
conversions. If database-specific conversions are required, they
466
should be made in the call to :meth:`get_db_prep_value`.
412
470
class HandField(models.Field):
415
def get_db_prep_value(self, value):
473
def get_prep_value(self, value):
416
474
return ''.join([''.join(l) for l in (value.north,
417
475
value.east, value.south, value.west)])
419
.. method:: get_db_prep_save(self, value)
421
Same as the above, but called when the Field value must be *saved* to the
422
database. As the default implementation just calls ``get_db_prep_value``, you
423
shouldn't need to implement this method unless your custom field needs a
424
special conversion when being saved that is not the same as the conversion used
425
for normal query parameters (which is implemented by ``get_db_prep_value``).
477
Converting query values to database values
478
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
480
.. method:: get_db_prep_value(self, value, connection, prepared=False)
482
.. versionadded:: 1.2
483
The ``connection`` and ``prepared`` arguments were added to support multiple databases.
485
Some data types (for example, dates) need to be in a specific format
486
before they can be used by a database backend.
487
:meth:`get_db_prep_value` is the method where those conversions should
488
be made. The specific connection that will be used for the query is
489
passed as the ``connection`` parameter. This allows you to use
490
backend-specific conversion logic if it is required.
492
The ``prepared`` argument describes whether or not the value has
493
already been passed through :meth:`get_prep_value` conversions. When
494
``prepared`` is False, the default implementation of
495
:meth:`get_db_prep_value` will call :meth:`get_prep_value` to do
496
initial data conversions before performing any database-specific
499
.. method:: get_db_prep_save(self, value, connection)
501
.. versionadded:: 1.2
502
The ``connection`` argument was added to support multiple databases.
504
Same as the above, but called when the Field value must be *saved* to
505
the database. As the default implementation just calls
506
``get_db_prep_value``, you shouldn't need to implement this method
507
unless your custom field needs a special conversion when being saved
508
that is not the same as the conversion used for normal query
509
parameters (which is implemented by ``get_db_prep_value``).
427
511
Preprocessing values before saving
428
512
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
450
534
Preparing values for use in database lookups
451
535
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
453
.. method:: get_db_prep_lookup(self, lookup_type, value)
537
As with value conversions, preparing a value for database lookups is a
540
.. method:: get_prep_lookup(self, lookup_type, value)
542
.. versionadded:: 1.2
543
This method was factored out of ``get_db_prep_lookup()``
545
:meth:`get_prep_lookup` performs the first phase of lookup preparation,
546
performing generic data validity checks
455
548
Prepares the ``value`` for passing to the database when used in a lookup (a
456
549
``WHERE`` constraint in SQL). The ``lookup_type`` will be one of the valid
467
560
and pass the rest to the :meth:`get_db_prep_lookup` method of the parent class.
469
562
If you needed to implement ``get_db_prep_save()``, you will usually need to
470
implement ``get_db_prep_lookup()``. If you don't, ``get_db_prep_value`` will be
563
implement ``get_prep_lookup()``. If you don't, ``get_prep_value`` will be
471
564
called by the default implementation, to manage ``exact``, ``gt``, ``gte``,
472
565
``lt``, ``lte``, ``in`` and ``range`` lookups.
474
567
You may also want to implement this method to limit the lookup types that could
475
568
be used with your custom field type.
477
Note that, for ``range`` and ``in`` lookups, ``get_db_prep_lookup`` will receive
570
Note that, for ``range`` and ``in`` lookups, ``get_prep_lookup`` will receive
478
571
a list of objects (presumably of the right type) and will need to convert them
479
572
to a list of things of the right type for passing to the database. Most of the
480
time, you can reuse ``get_db_prep_value()``, or at least factor out some common
573
time, you can reuse ``get_prep_value()``, or at least factor out some common
483
For example, the following code implements ``get_db_prep_lookup`` to limit the
576
For example, the following code implements ``get_prep_lookup`` to limit the
484
577
accepted lookup types to ``exact`` and ``in``::
486
579
class HandField(models.Field):
489
def get_db_prep_lookup(self, lookup_type, value):
582
def get_prep_lookup(self, lookup_type, value):
490
583
# We only handle 'exact' and 'in'. All others are errors.
491
584
if lookup_type == 'exact':
492
return [self.get_db_prep_value(value)]
585
return self.get_prep_value(value)
493
586
elif lookup_type == 'in':
494
return [self.get_db_prep_value(v) for v in value]
587
return [self.get_prep_value(v) for v in value]
496
589
raise TypeError('Lookup type %r not supported.' % lookup_type)
591
.. method:: get_db_prep_lookup(self, lookup_type, value, connection, prepared=False)
593
.. versionadded:: 1.2
594
The ``connection`` and ``prepared`` arguments were added to support multiple databases.
596
Performs any database-specific data conversions required by a lookup.
597
As with :meth:`get_db_prep_value`, the specific connection that will
598
be used for the query is passed as the ``connection`` parameter.
599
The ``prepared`` argument describes whether the value has already been
600
prepared with :meth:`get_prep_lookup`.
498
602
Specifying the form field for a model field
499
603
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~