~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to docs/howto/custom-model-fields.txt

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
5
5
===========================
6
6
 
7
7
.. versionadded:: 1.0
 
8
.. currentmodule:: django.db.models
8
9
 
9
10
Introduction
10
11
============
39
40
something like this::
40
41
 
41
42
    class Hand(object):
 
43
        """A hand of cards (bridge style)"""
 
44
 
42
45
        def __init__(self, north, east, south, west):
43
46
            # Input parameters are lists of cards ('Ah', '9s', etc)
44
47
            self.north = north
163
166
    from django.db import models
164
167
 
165
168
    class HandField(models.Field):
 
169
 
 
170
        description = "A hand of cards (bridge style)"
 
171
 
166
172
        def __init__(self, *args, **kwargs):
167
173
            kwargs['max_length'] = 104
168
174
            super(HandField, self).__init__(*args, **kwargs)
244
250
For example::
245
251
 
246
252
    class HandField(models.Field):
 
253
 
 
254
        description = "A hand of cards (bridge style)"
 
255
 
247
256
        __metaclass__ = models.SubfieldBase
248
257
 
249
258
        def __init__(self, *args, **kwargs):
252
261
This ensures that the :meth:`to_python` method, documented below, will always be
253
262
called when the attribute is initialized.
254
263
 
 
264
ModelForms and custom fields
 
265
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
266
 
 
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.
 
272
 
 
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.
 
278
 
 
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
 
285
correct datatype.
 
286
 
 
287
Documenting your Custom Field
 
288
-----------------------------
 
289
 
 
290
.. class:: django.db.models.Field
 
291
 
 
292
.. attribute:: description
 
293
 
 
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)'.
 
301
 
255
302
Useful methods
256
303
--------------
257
304
 
263
310
Custom database types
264
311
~~~~~~~~~~~~~~~~~~~~~
265
312
 
266
 
.. method:: db_type(self)
 
313
.. method:: db_type(self, connection)
 
314
 
 
315
.. versionadded:: 1.2
 
316
   The ``connection`` argument was added to support multiple databases.
267
317
 
268
318
Returns the database column data type for the :class:`~django.db.models.Field`,
269
 
taking into account the current :setting:`DATABASE_ENGINE` setting.
 
319
taking into account the connection object, and the settings associated with it.
270
320
 
271
321
Say you've created a PostgreSQL custom type called ``mytype``. You can use this
272
322
field with Django by subclassing ``Field`` and implementing the :meth:`db_type`
275
325
    from django.db import models
276
326
 
277
327
    class MytypeField(models.Field):
278
 
        def db_type(self):
 
328
        def db_type(self, connection):
279
329
            return 'mytype'
280
330
 
281
331
Once you have ``MytypeField``, you can use it in any model, just like any other
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.
 
344
 
294
345
For example::
295
346
 
296
347
    class MyDateField(models.Field):
297
 
        def db_type(self):
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'
301
351
            else:
302
352
                return 'timestamp'
304
354
The :meth:`db_type` method is only called by Django when the framework
305
355
constructs the ``CREATE TABLE`` statements for your application -- that is, when
306
356
you first create your tables. It's not called at any other time, so it can
307
 
afford to execute slightly complex code, such as the :setting:`DATABASE_ENGINE`
 
357
afford to execute slightly complex code, such as the ``connection.settings_dict``
308
358
check in the above example.
309
359
 
310
360
Some database column types accept parameters, such as ``CHAR(25)``, where the
315
365
 
316
366
    # This is a silly example of hard-coded parameters.
317
367
    class CharMaxlength25Field(models.Field):
318
 
        def db_type(self):
 
368
        def db_type(self, connection):
319
369
            return 'char(25)'
320
370
 
321
371
    # In the model:
333
383
            self.max_length = max_length
334
384
            super(BetterCharField, self).__init__(*args, **kwargs)
335
385
 
336
 
        def db_type(self):
 
386
        def db_type(self, connection):
337
387
            return 'char(%s)' % self.max_length
338
388
 
339
389
    # In the model:
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.
398
448
 
399
 
Converting Python objects to database values
400
 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
401
 
 
402
 
.. method:: get_db_prep_value(self, value)
403
 
 
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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
451
 
 
452
.. method:: get_prep_value(self, value)
 
453
 
 
454
.. versionadded:: 1.2
 
455
   This method was factored out of ``get_db_prep_value()``
 
456
 
 
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.
 
463
 
 
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`.
409
467
 
410
468
For example::
411
469
 
412
470
    class HandField(models.Field):
413
471
        # ...
414
472
 
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)])
418
476
 
419
 
.. method:: get_db_prep_save(self, value)
420
 
 
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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
479
 
 
480
.. method:: get_db_prep_value(self, value, connection, prepared=False)
 
481
 
 
482
.. versionadded:: 1.2
 
483
   The ``connection`` and ``prepared`` arguments were added to support multiple databases.
 
484
 
 
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.
 
491
 
 
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
 
497
processing.
 
498
 
 
499
.. method:: get_db_prep_save(self, value, connection)
 
500
 
 
501
.. versionadded:: 1.2
 
502
   The ``connection`` argument was added to support multiple databases.
 
503
 
 
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``).
426
510
 
427
511
Preprocessing values before saving
428
512
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
450
534
Preparing values for use in database lookups
451
535
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452
536
 
453
 
.. method:: get_db_prep_lookup(self, lookup_type, value)
 
537
As with value conversions, preparing a value for database lookups is a
 
538
two phase process.
 
539
 
 
540
.. method:: get_prep_lookup(self, lookup_type, value)
 
541
 
 
542
.. versionadded:: 1.2
 
543
   This method was factored out of ``get_db_prep_lookup()``
 
544
 
 
545
:meth:`get_prep_lookup` performs the first phase of lookup preparation,
 
546
performing generic data validity checks
454
547
 
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.
468
561
 
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.
473
566
 
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.
476
569
 
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
481
574
pieces.
482
575
 
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``::
485
578
 
486
579
    class HandField(models.Field):
487
580
        # ...
488
581
 
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]
495
588
            else:
496
589
                raise TypeError('Lookup type %r not supported.' % lookup_type)
497
590
 
 
591
.. method:: get_db_prep_lookup(self, lookup_type, value, connection, prepared=False)
 
592
 
 
593
.. versionadded:: 1.2
 
594
   The ``connection`` and ``prepared`` arguments were added to support multiple databases.
 
595
 
 
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`.
 
601
 
498
602
Specifying the form field for a model field
499
603
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
500
604