/docs/ref/models/fields.txt
Plain Text | 1140 lines | 777 code | 363 blank | 0 comment | 0 complexity | ddd5019ec8fbdfa91914b4873ad0af50 MD5 | raw file
1===================== 2Model field reference 3===================== 4 5.. module:: django.db.models.fields 6 :synopsis: Built-in field types. 7 8.. currentmodule:: django.db.models 9 10This document contains all the gory details about all the `field options`_ and 11`field types`_ Django's got to offer. 12 13.. seealso:: 14 15 If the built-in fields don't do the trick, you can try 16 :mod:`django.contrib.localflavor`, which contains assorted pieces of code 17 that are useful for particular countries or cultures. Also, you can easily 18 :doc:`write your own custom model fields </howto/custom-model-fields>`. 19 20.. note:: 21 22 Technically, these models are defined in :mod:`django.db.models.fields`, but 23 for convenience they're imported into :mod:`django.db.models`; the standard 24 convention is to use ``from django.db import models`` and refer to fields as 25 ``models.<Foo>Field``. 26 27.. _common-model-field-options: 28 29Field options 30============= 31 32The following arguments are available to all field types. All are optional. 33 34``null`` 35-------- 36 37.. attribute:: Field.null 38 39If ``True``, Django will store empty values as ``NULL`` in the database. Default 40is ``False``. 41 42Note that empty string values will always get stored as empty strings, not as 43``NULL``. Only use ``null=True`` for non-string fields such as integers, 44booleans and dates. For both types of fields, you will also need to set 45``blank=True`` if you wish to permit empty values in forms, as the 46:attr:`~Field.null` parameter only affects database storage (see 47:attr:`~Field.blank`). 48 49Avoid using :attr:`~Field.null` on string-based fields such as 50:class:`CharField` and :class:`TextField` unless you have an excellent reason. 51If a string-based field has ``null=True``, that means it has two possible values 52for "no data": ``NULL``, and the empty string. In most cases, it's redundant to 53have two possible values for "no data;" Django convention is to use the empty 54string, not ``NULL``. 55 56.. note:: 57 58 When using the Oracle database backend, the ``null=True`` option will be 59 coerced for string-based fields that have the empty string as a possible 60 value, and the value ``NULL`` will be stored to denote the empty string. 61 62``blank`` 63--------- 64 65.. attribute:: Field.blank 66 67If ``True``, the field is allowed to be blank. Default is ``False``. 68 69Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is 70purely database-related, whereas :attr:`~Field.blank` is validation-related. If 71a field has ``blank=True``, validation on Django's admin site will allow entry 72of an empty value. If a field has ``blank=False``, the field will be required. 73 74.. _field-choices: 75 76``choices`` 77----------- 78 79.. attribute:: Field.choices 80 81An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this 82field. 83 84If this is given, Django's admin will use a select box instead of the standard 85text field and will limit choices to the choices given. 86 87A choices list looks like this:: 88 89 YEAR_IN_SCHOOL_CHOICES = ( 90 ('FR', 'Freshman'), 91 ('SO', 'Sophomore'), 92 ('JR', 'Junior'), 93 ('SR', 'Senior'), 94 ('GR', 'Graduate'), 95 ) 96 97The first element in each tuple is the actual value to be stored. The second 98element is the human-readable name for the option. 99 100The choices list can be defined either as part of your model class:: 101 102 class Foo(models.Model): 103 GENDER_CHOICES = ( 104 ('M', 'Male'), 105 ('F', 'Female'), 106 ) 107 gender = models.CharField(max_length=1, choices=GENDER_CHOICES) 108 109or outside your model class altogether:: 110 111 GENDER_CHOICES = ( 112 ('M', 'Male'), 113 ('F', 'Female'), 114 ) 115 class Foo(models.Model): 116 gender = models.CharField(max_length=1, choices=GENDER_CHOICES) 117 118You can also collect your available choices into named groups that can 119be used for organizational purposes:: 120 121 MEDIA_CHOICES = ( 122 ('Audio', ( 123 ('vinyl', 'Vinyl'), 124 ('cd', 'CD'), 125 ) 126 ), 127 ('Video', ( 128 ('vhs', 'VHS Tape'), 129 ('dvd', 'DVD'), 130 ) 131 ), 132 ('unknown', 'Unknown'), 133 ) 134 135The first element in each tuple is the name to apply to the group. The 136second element is an iterable of 2-tuples, with each 2-tuple containing 137a value and a human-readable name for an option. Grouped options may be 138combined with ungrouped options within a single list (such as the 139`unknown` option in this example). 140 141For each model field that has :attr:`~Field.choices` set, Django will add a 142method to retrieve the human-readable name for the field's current value. See 143:meth:`~django.db.models.Model.get_FOO_display` in the database API 144documentation. 145 146Finally, note that choices can be any iterable object -- not necessarily a list 147or tuple. This lets you construct choices dynamically. But if you find yourself 148hacking :attr:`~Field.choices` to be dynamic, you're probably better off using a 149proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is 150meant for static data that doesn't change much, if ever. 151 152``db_column`` 153------------- 154 155.. attribute:: Field.db_column 156 157The name of the database column to use for this field. If this isn't given, 158Django will use the field's name. 159 160If your database column name is an SQL reserved word, or contains 161characters that aren't allowed in Python variable names -- notably, the 162hyphen -- that's OK. Django quotes column and table names behind the 163scenes. 164 165``db_index`` 166------------ 167 168.. attribute:: Field.db_index 169 170If ``True``, djadmin:`django-admin.py sqlindexes <sqlindexes>` will output a 171``CREATE INDEX`` statement for this field. 172 173``db_tablespace`` 174----------------- 175 176.. attribute:: Field.db_tablespace 177 178The name of the database tablespace to use for this field's index, if this field 179is indexed. The default is the project's :setting:`DEFAULT_INDEX_TABLESPACE` 180setting, if set, or the :attr:`~Field.db_tablespace` of the model, if any. If 181the backend doesn't support tablespaces, this option is ignored. 182 183``default`` 184----------- 185 186.. attribute:: Field.default 187 188The default value for the field. This can be a value or a callable object. If 189callable it will be called every time a new object is created. 190 191``editable`` 192------------ 193 194.. attribute:: Field.editable 195 196If ``False``, the field will not be editable in the admin or via forms 197automatically generated from the model class. Default is ``True``. 198 199``error_messages`` 200------------------ 201 202.. versionadded:: 1.2 203 204.. attribute:: Field.error_messages 205 206The ``error_messages`` argument lets you override the default messages that the 207field will raise. Pass in a dictionary with keys matching the error messages you 208want to override. 209 210``help_text`` 211------------- 212 213.. attribute:: Field.help_text 214 215Extra "help" text to be displayed under the field on the object's admin form. 216It's useful for documentation even if your object doesn't have an admin form. 217 218Note that this value is *not* HTML-escaped when it's displayed in the admin 219interface. This lets you include HTML in :attr:`~Field.help_text` if you so 220desire. For example:: 221 222 help_text="Please use the following format: <em>YYYY-MM-DD</em>." 223 224Alternatively you can use plain text and 225``django.utils.html.escape()`` to escape any HTML special characters. 226 227``primary_key`` 228--------------- 229 230.. attribute:: Field.primary_key 231 232If ``True``, this field is the primary key for the model. 233 234If you don't specify ``primary_key=True`` for any fields in your model, Django 235will automatically add an :class:`IntegerField` to hold the primary key, so you 236don't need to set ``primary_key=True`` on any of your fields unless you want to 237override the default primary-key behavior. For more, see 238:ref:`automatic-primary-key-fields`. 239 240``primary_key=True`` implies :attr:`null=False <Field.null>` and :attr:`unique=True <Field.unique>`. 241Only one primary key is allowed on an object. 242 243``unique`` 244---------- 245 246.. attribute:: Field.unique 247 248If ``True``, this field must be unique throughout the table. 249 250This is enforced at the database level and at the Django admin-form level. If 251you try to save a model with a duplicate value in a :attr:`~Field.unique` 252field, a :exc:`django.db.IntegrityError` will be raised by the model's 253:meth:`~django.db.models.Model.save` method. 254 255This option is valid on all field types except :class:`ManyToManyField` and 256:class:`FileField`. 257 258``unique_for_date`` 259------------------- 260 261.. attribute:: Field.unique_for_date 262 263Set this to the name of a :class:`DateField` or :class:`DateTimeField` to 264require that this field be unique for the value of the date field. 265 266For example, if you have a field ``title`` that has 267``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two 268records with the same ``title`` and ``pub_date``. 269 270This is enforced at the Django admin-form level but not at the database level. 271 272``unique_for_month`` 273-------------------- 274 275.. attribute:: Field.unique_for_month 276 277Like :attr:`~Field.unique_for_date`, but requires the field to be unique with 278respect to the month. 279 280``unique_for_year`` 281------------------- 282 283.. attribute:: Field.unique_for_year 284 285Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`. 286 287``verbose_name`` 288------------------- 289 290.. attribute:: Field.verbose_name 291 292A human-readable name for the field. If the verbose name isn't given, Django 293will automatically create it using the field's attribute name, converting 294underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`. 295 296``validators`` 297------------------- 298 299.. versionadded:: 1.2 300 301.. attribute:: Field.validators 302 303A list of validators to run for this field.See the :doc:`validators 304documentation </ref/validators>` for more information. 305 306.. _model-field-types: 307 308Field types 309=========== 310 311.. currentmodule:: django.db.models 312 313``AutoField`` 314------------- 315 316.. class:: AutoField(**options) 317 318An :class:`IntegerField` that automatically increments 319according to available IDs. You usually won't need to use this directly; a 320primary key field will automatically be added to your model if you don't specify 321otherwise. See :ref:`automatic-primary-key-fields`. 322 323``BigIntegerField`` 324------------------- 325 326.. versionadded:: 1.2 327 328.. class:: BigIntegerField([**options]) 329 330A 64 bit integer, much like an :class:`IntegerField` except that it is 331guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The 332admin represents this as an ``<input type="text">`` (a single-line input). 333 334 335``BooleanField`` 336---------------- 337 338.. class:: BooleanField(**options) 339 340A true/false field. 341 342The admin represents this as a checkbox. 343 344.. versionchanged:: 1.2 345 346 In previous versions of Django when running under MySQL ``BooleanFields`` 347 would return their data as ``ints``, instead of true ``bools``. See the 348 release notes for a complete description of the change. 349 350``CharField`` 351------------- 352 353.. class:: CharField(max_length=None, [**options]) 354 355A string field, for small- to large-sized strings. 356 357For large amounts of text, use :class:`~django.db.models.TextField`. 358 359The admin represents this as an ``<input type="text">`` (a single-line input). 360 361:class:`CharField` has one extra required argument: 362 363.. attribute:: CharField.max_length 364 365 The maximum length (in characters) of the field. The max_length is enforced 366 at the database level and in Django's validation. 367 368.. note:: 369 370 If you are writing an application that must be portable to multiple 371 database backends, you should be aware that there are restrictions on 372 ``max_length`` for some backends. Refer to the :doc:`database backend 373 notes </ref/databases>` for details. 374 375.. admonition:: MySQL users 376 377 If you are using this field with MySQLdb 1.2.2 and the ``utf8_bin`` 378 collation (which is *not* the default), there are some issues to be aware 379 of. Refer to the :ref:`MySQL database notes <mysql-collation>` for 380 details. 381 382 383``CommaSeparatedIntegerField`` 384------------------------------ 385 386.. class:: CommaSeparatedIntegerField(max_length=None, [**options]) 387 388A field of integers separated by commas. As in :class:`CharField`, the 389:attr:`~CharField.max_length` argument is required and the note about database 390portability mentioned there should be heeded. 391 392``DateField`` 393------------- 394 395.. class:: DateField([auto_now=False, auto_now_add=False, **options]) 396 397A date, represented in Python by a ``datetime.date`` instance. Has a few extra, 398optional arguments: 399 400.. attribute:: DateField.auto_now 401 402 Automatically set the field to now every time the object is saved. Useful 403 for "last-modified" timestamps. Note that the current date is *always* 404 used; it's not just a default value that you can override. 405 406.. attribute:: DateField.auto_now_add 407 408 Automatically set the field to now when the object is first created. Useful 409 for creation of timestamps. Note that the current date is *always* used; 410 it's not just a default value that you can override. 411 412The admin represents this as an ``<input type="text">`` with a JavaScript 413calendar, and a shortcut for "Today". The JavaScript calendar will always 414start the week on a Sunday. 415 416.. note:: 417 As currently implemented, setting ``auto_now`` or ``auto_now_add`` to 418 ``True`` will cause the field to have ``editable=False`` and ``blank=True`` 419 set. 420 421``DateTimeField`` 422----------------- 423 424.. class:: DateTimeField([auto_now=False, auto_now_add=False, **options]) 425 426A date and time, represented in Python by a ``datetime.datetime`` instance. 427Takes the same extra arguments as :class:`DateField`. 428 429The admin represents this as two ``<input type="text">`` fields, with 430JavaScript shortcuts. 431 432``DecimalField`` 433---------------- 434 435.. class:: DecimalField(max_digits=None, decimal_places=None, [**options]) 436 437A fixed-precision decimal number, represented in Python by a 438:class:`~decimal.Decimal` instance. Has two **required** arguments: 439 440.. attribute:: DecimalField.max_digits 441 442 The maximum number of digits allowed in the number. Note that this number 443 must be greater than ``decimal_places``, if it exists. 444 445.. attribute:: DecimalField.decimal_places 446 447 The number of decimal places to store with the number. 448 449For example, to store numbers up to 999 with a resolution of 2 decimal places, 450you'd use:: 451 452 models.DecimalField(..., max_digits=5, decimal_places=2) 453 454And to store numbers up to approximately one billion with a resolution of 10 455decimal places:: 456 457 models.DecimalField(..., max_digits=19, decimal_places=10) 458 459The admin represents this as an ``<input type="text">`` (a single-line input). 460 461.. note:: 462 463 For more information about the differences between the 464 :class:`FloatField` and :class:`DecimalField` classes, please 465 see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`. 466 467``EmailField`` 468-------------- 469 470.. class:: EmailField([max_length=75, **options]) 471 472A :class:`CharField` that checks that the value is a valid e-mail address. 473 474``FileField`` 475------------- 476 477.. class:: FileField(upload_to=None, [max_length=100, **options]) 478 479A file-upload field. 480 481.. note:: 482 The ``primary_key`` and ``unique`` arguments are not supported, and will 483 raise a ``TypeError`` if used. 484 485Has one **required** argument: 486 487.. attribute:: FileField.upload_to 488 489 A local filesystem path that will be appended to your :setting:`MEDIA_ROOT` 490 setting to determine the value of the :attr:`~django.core.files.File.url` 491 attribute. 492 493 This path may contain `strftime formatting`_, which will be replaced by the 494 date/time of the file upload (so that uploaded files don't fill up the given 495 directory). 496 497 This may also be a callable, such as a function, which will be called to 498 obtain the upload path, including the filename. This callable must be able 499 to accept two arguments, and return a Unix-style path (with forward slashes) 500 to be passed along to the storage system. The two arguments that will be 501 passed are: 502 503 ====================== =============================================== 504 Argument Description 505 ====================== =============================================== 506 ``instance`` An instance of the model where the 507 ``FileField`` is defined. More specifically, 508 this is the particular instance where the 509 current file is being attached. 510 511 In most cases, this object will not have been 512 saved to the database yet, so if it uses the 513 default ``AutoField``, *it might not yet have a 514 value for its primary key field*. 515 516 ``filename`` The filename that was originally given to the 517 file. This may or may not be taken into account 518 when determining the final destination path. 519 ====================== =============================================== 520 521Also has one optional argument: 522 523.. attribute:: FileField.storage 524 525 Optional. A storage object, which handles the storage and retrieval of your 526 files. See :doc:`/topics/files` for details on how to provide this object. 527 528The admin represents this field as an ``<input type="file">`` (a file-upload 529widget). 530 531Using a :class:`FileField` or an :class:`ImageField` (see below) in a model 532takes a few steps: 533 534 1. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the 535 full path to a directory where you'd like Django to store uploaded files. 536 (For performance, these files are not stored in the database.) Define 537 :setting:`MEDIA_URL` as the base public URL of that directory. Make sure 538 that this directory is writable by the Web server's user account. 539 540 2. Add the :class:`FileField` or :class:`ImageField` to your model, making 541 sure to define the :attr:`~FileField.upload_to` option to tell Django 542 to which subdirectory of :setting:`MEDIA_ROOT` it should upload files. 543 544 3. All that will be stored in your database is a path to the file 545 (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the 546 convenience :attr:`~django.core.files.File.url` function provided by 547 Django. For example, if your :class:`ImageField` is called ``mug_shot``, 548 you can get the absolute path to your image in a template with 549 ``{{ object.mug_shot.url }}``. 550 551For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and 552:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'`` 553part of :attr:`~FileField.upload_to` is `strftime formatting`_; ``'%Y'`` is the 554four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is the two-digit 555day. If you upload a file on Jan. 15, 2007, it will be saved in the directory 556``/home/media/photos/2007/01/15``. 557 558If you wanted to retrieve the uploaded file's on-disk filename, or the file's 559size, you could use the :attr:`~django.core.files.File.name` and 560:attr:`~django.core.files.File.size` attributes respectively; for more 561information on the available attributes and methods, see the 562:class:`~django.core.files.File` class reference and the :doc:`/topics/files` 563topic guide. 564 565The uploaded file's relative URL can be obtained using the 566:attr:`~django.db.models.fields.FileField.url` attribute. Internally, 567this calls the :meth:`~django.core.files.storage.Storage.url` method of the 568underlying :class:`~django.core.files.storage.Storage` class. 569 570Note that whenever you deal with uploaded files, you should pay close attention 571to where you're uploading them and what type of files they are, to avoid 572security holes. *Validate all uploaded files* so that you're sure the files are 573what you think they are. For example, if you blindly let somebody upload files, 574without validation, to a directory that's within your Web server's document 575root, then somebody could upload a CGI or PHP script and execute that script by 576visiting its URL on your site. Don't allow that. 577 578By default, :class:`FileField` instances are 579created as ``varchar(100)`` columns in your database. As with other fields, you 580can change the maximum length using the :attr:`~CharField.max_length` argument. 581 582.. _`strftime formatting`: http://docs.python.org/library/time.html#time.strftime 583 584FileField and FieldFile 585~~~~~~~~~~~~~~~~~~~~~~~ 586 587When you access a :class:`FileField` on a model, you are given an instance 588of :class:`FieldFile` as a proxy for accessing the underlying file. This 589class has several methods that can be used to interact with file data: 590 591.. method:: FieldFile.open(mode='rb') 592 593Behaves like the standard Python ``open()`` method and opens the file 594associated with this instance in the mode specified by ``mode``. 595 596.. method:: FieldFile.close() 597 598Behaves like the standard Python ``file.close()`` method and closes the file 599associated with this instance. 600 601.. method:: FieldFile.save(name, content, save=True) 602 603This method takes a filename and file contents and passes them to the storage 604class for the field, then associates the stored file with the model field. 605If you want to manually associate file data with :class:`FileField` 606instances on your model, the ``save()`` method is used to persist that file 607data. 608 609Takes two required arguments: ``name`` which is the name of the file, and 610``content`` which is an object containing the file's contents. The 611optional ``save`` argument controls whether or not the instance is 612saved after the file has been altered. Defaults to ``True``. 613 614Note that the ``content`` argument should be an instance of 615:class:`django.core.files.File`, not Python's built-in file object. 616You can construct a :class:`~django.core.files.File` from an existing 617Python file object like this:: 618 619 from django.core.files import File 620 # Open an existing file using Python's built-in open() 621 f = open('/tmp/hello.world') 622 myfile = File(f) 623 624Or you can construct one from a Python string like this:: 625 626 from django.core.files.base import ContentFile 627 myfile = ContentFile("hello world") 628 629For more information, see :doc:`/topics/files`. 630 631.. method:: FieldFile.delete(save=True) 632 633Deletes the file associated with this instance and clears all attributes on 634the field. Note: This method will close the file if it happens to be open when 635``delete()`` is called. 636 637The optional ``save`` argument controls whether or not the instance is saved 638after the file has been deleted. Defaults to ``True``. 639 640``FilePathField`` 641----------------- 642 643.. class:: FilePathField(path=None, [match=None, recursive=False, max_length=100, **options]) 644 645A :class:`CharField` whose choices are limited to the filenames in a certain 646directory on the filesystem. Has three special arguments, of which the first is 647**required**: 648 649.. attribute:: FilePathField.path 650 651 Required. The absolute filesystem path to a directory from which this 652 :class:`FilePathField` should get its choices. Example: ``"/home/images"``. 653 654.. attribute:: FilePathField.match 655 656 Optional. A regular expression, as a string, that :class:`FilePathField` 657 will use to filter filenames. Note that the regex will be applied to the 658 base filename, not the full path. Example: ``"foo.*\.txt$"``, which will 659 match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``. 660 661.. attribute:: FilePathField.recursive 662 663 Optional. Either ``True`` or ``False``. Default is ``False``. Specifies 664 whether all subdirectories of :attr:`~FilePathField.path` should be included 665 666Of course, these arguments can be used together. 667 668The one potential gotcha is that :attr:`~FilePathField.match` applies to the 669base filename, not the full path. So, this example:: 670 671 FilePathField(path="/home/images", match="foo.*", recursive=True) 672 673...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif`` 674because the :attr:`~FilePathField.match` applies to the base filename 675(``foo.gif`` and ``bar.gif``). 676 677By default, :class:`FilePathField` instances are 678created as ``varchar(100)`` columns in your database. As with other fields, you 679can change the maximum length using the :attr:`~CharField.max_length` argument. 680 681``FloatField`` 682-------------- 683 684.. class:: FloatField([**options]) 685 686A floating-point number represented in Python by a ``float`` instance. 687 688The admin represents this as an ``<input type="text">`` (a single-line input). 689 690.. _floatfield_vs_decimalfield: 691 692.. admonition:: ``FloatField`` vs. ``DecimalField`` 693 694 The :class:`FloatField` class is sometimes mixed up with the 695 :class:`DecimalField` class. Although they both represent real numbers, they 696 represent those numbers differently. ``FloatField`` uses Python's ``float`` 697 type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For 698 information on the difference between the two, see Python's documentation on 699 `Decimal fixed point and floating point arithmetic`_. 700 701.. _Decimal fixed point and floating point arithmetic: http://docs.python.org/library/decimal.html 702 703 704``ImageField`` 705-------------- 706 707.. class:: ImageField(upload_to=None, [height_field=None, width_field=None, max_length=100, **options]) 708 709Inherits all attributes and methods from :class:`FileField`, but also 710validates that the uploaded object is a valid image. 711 712In addition to the special attributes that are available for :class:`FileField`, 713an :class:`ImageField` also has :attr:`~django.core.files.File.height` and 714:attr:`~django.core.files.File.width` attributes. 715 716To facilitate querying on those attributes, :class:`ImageField` has two extra 717optional arguments: 718 719.. attribute:: ImageField.height_field 720 721 Name of a model field which will be auto-populated with the height of the 722 image each time the model instance is saved. 723 724.. attribute:: ImageField.width_field 725 726 Name of a model field which will be auto-populated with the width of the 727 image each time the model instance is saved. 728 729Requires the `Python Imaging Library`_. 730 731.. _Python Imaging Library: http://www.pythonware.com/products/pil/ 732 733By default, :class:`ImageField` instances are created as ``varchar(100)`` 734columns in your database. As with other fields, you can change the maximum 735length using the :attr:`~CharField.max_length` argument. 736 737``IntegerField`` 738---------------- 739 740.. class:: IntegerField([**options]) 741 742An integer. The admin represents this as an ``<input type="text">`` (a 743single-line input). 744 745``IPAddressField`` 746------------------ 747 748.. class:: IPAddressField([**options]) 749 750An IP address, in string format (e.g. "192.0.2.30"). The admin represents this 751as an ``<input type="text">`` (a single-line input). 752 753``NullBooleanField`` 754-------------------- 755 756.. class:: NullBooleanField([**options]) 757 758Like a :class:`BooleanField`, but allows ``NULL`` as one of the options. Use 759this instead of a :class:`BooleanField` with ``null=True``. The admin represents 760this as a ``<select>`` box with "Unknown", "Yes" and "No" choices. 761 762``PositiveIntegerField`` 763------------------------ 764 765.. class:: PositiveIntegerField([**options]) 766 767Like an :class:`IntegerField`, but must be positive. 768 769``PositiveSmallIntegerField`` 770----------------------------- 771 772.. class:: PositiveSmallIntegerField([**options]) 773 774Like a :class:`PositiveIntegerField`, but only allows values under a certain 775(database-dependent) point. 776 777``SlugField`` 778------------- 779 780.. class:: SlugField([max_length=50, **options]) 781 782:term:`Slug` is a newspaper term. A slug is a short label for something, 783containing only letters, numbers, underscores or hyphens. They're generally used 784in URLs. 785 786Like a CharField, you can specify :attr:`~CharField.max_length` (read the note 787about database portability and :attr:`~CharField.max_length` in that section, 788too). If :attr:`~CharField.max_length` is not specified, Django will use a 789default length of 50. 790 791Implies setting :attr:`Field.db_index` to ``True``. 792 793It is often useful to automatically prepopulate a SlugField based on the value 794of some other value. You can do this automatically in the admin using 795:attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`. 796 797``SmallIntegerField`` 798--------------------- 799 800.. class:: SmallIntegerField([**options]) 801 802Like an :class:`IntegerField`, but only allows values under a certain 803(database-dependent) point. 804 805``TextField`` 806------------- 807 808.. class:: TextField([**options]) 809 810A large text field. The admin represents this as a ``<textarea>`` (a multi-line 811input). 812 813.. admonition:: MySQL users 814 815 If you are using this field with MySQLdb 1.2.1p2 and the ``utf8_bin`` 816 collation (which is *not* the default), there are some issues to be aware 817 of. Refer to the :ref:`MySQL database notes <mysql-collation>` for 818 details. 819 820``TimeField`` 821------------- 822 823.. class:: TimeField([auto_now=False, auto_now_add=False, **options]) 824 825A time, represented in Python by a ``datetime.time`` instance. Accepts the same 826auto-population options as :class:`DateField`. 827 828The admin represents this as an ``<input type="text">`` with some JavaScript 829shortcuts. 830 831``URLField`` 832------------ 833 834.. class:: URLField([verify_exists=False, max_length=200, **options]) 835 836A :class:`CharField` for a URL. Has one extra optional argument: 837 838.. deprecated:: 1.3.1 839 840 ``verify_exists`` is deprecated for security reasons as of 1.3.1 841 and will be removed in 1.4. Prior to 1.3.1, the default value was 842 ``True``. 843 844.. attribute:: URLField.verify_exists 845 846 If ``True``, the URL given will be checked for existence (i.e., 847 the URL actually loads and doesn't give a 404 response) using a 848 ``HEAD`` request. Redirects are allowed, but will not be followed. 849 850 Note that when you're using the single-threaded development server, 851 validating a URL being served by the same server will hang. This should not 852 be a problem for multithreaded servers. 853 854The admin represents this as an ``<input type="text">`` (a single-line input). 855 856Like all :class:`CharField` subclasses, :class:`URLField` takes the optional 857:attr:`~CharField.max_length`argument. If you don't specify 858:attr:`~CharField.max_length`, a default of 200 is used. 859 860``XMLField`` 861------------ 862 863.. deprecated:: 1.3 864 ``XMLField`` is deprecated. Use TextField instead. 865 866.. class:: XMLField(schema_path=None, [**options]) 867 868A :class:`TextField` that stores XML data and a path to a schema. Takes one 869optional argument: 870 871.. attribute:: schema_path 872 873 The filesystem path to a schema for the field. 874 875 876Relationship fields 877=================== 878 879.. module:: django.db.models.fields.related 880 :synopsis: Related field types 881 882.. currentmodule:: django.db.models 883 884Django also defines a set of fields that represent relations. 885 886.. _ref-foreignkey: 887 888``ForeignKey`` 889-------------- 890 891.. class:: ForeignKey(othermodel, [**options]) 892 893A many-to-one relationship. Requires a positional argument: the class to which 894the model is related. 895 896.. _recursive-relationships: 897 898To create a recursive relationship -- an object that has a many-to-one 899relationship with itself -- use ``models.ForeignKey('self')``. 900 901.. _lazy-relationships: 902 903If you need to create a relationship on a model that has not yet been defined, 904you can use the name of the model, rather than the model object itself:: 905 906 class Car(models.Model): 907 manufacturer = models.ForeignKey('Manufacturer') 908 # ... 909 910 class Manufacturer(models.Model): 911 # ... 912 913To refer to models defined in another application, you can explicitly specify 914a model with the full application label. For example, if the ``Manufacturer`` 915model above is defined in another application called ``production``, you'd 916need to use:: 917 918 class Car(models.Model): 919 manufacturer = models.ForeignKey('production.Manufacturer') 920 921This sort of reference can be useful when resolving circular import 922dependencies between two applications. 923 924Database Representation 925~~~~~~~~~~~~~~~~~~~~~~~ 926 927Behind the scenes, Django appends ``"_id"`` to the field name to create its 928database column name. In the above example, the database table for the ``Car`` 929model will have a ``manufacturer_id`` column. (You can change this explicitly by 930specifying :attr:`~Field.db_column`) However, your code should never have to 931deal with the database column name, unless you write custom SQL. You'll always 932deal with the field names of your model object. 933 934.. _foreign-key-arguments: 935 936Arguments 937~~~~~~~~~ 938 939:class:`ForeignKey` accepts an extra set of arguments -- all optional -- that 940define the details of how the relation works. 941 942.. attribute:: ForeignKey.limit_choices_to 943 944 A dictionary of lookup arguments and values (see :doc:`/topics/db/queries`) 945 that limit the available admin choices for this object. Use this with 946 functions from the Python ``datetime`` module to limit choices of objects by 947 date. For example:: 948 949 limit_choices_to = {'pub_date__lte': datetime.now} 950 951 only allows the choice of related objects with a ``pub_date`` before the 952 current date/time to be chosen. 953 954 Instead of a dictionary this can also be a :class:`~django.db.models.Q` 955 object for more :ref:`complex queries <complex-lookups-with-q>`. However, 956 if ``limit_choices_to`` is a :class:`~django.db.models.Q` object then it 957 will only have an effect on the choices available in the admin when the 958 field is not listed in ``raw_id_fields`` in the ``ModelAdmin`` for the model. 959 960.. attribute:: ForeignKey.related_name 961 962 The name to use for the relation from the related object back to this one. 963 See the :ref:`related objects documentation <backwards-related-objects>` for 964 a full explanation and example. Note that you must set this value 965 when defining relations on :ref:`abstract models 966 <abstract-base-classes>`; and when you do so 967 :ref:`some special syntax <abstract-related-name>` is available. 968 969 If you'd prefer Django didn't create a backwards relation, set ``related_name`` 970 to ``'+'``. For example, this will ensure that the ``User`` model won't get a 971 backwards relation to this model:: 972 973 user = models.ForeignKey(User, related_name='+') 974 975.. attribute:: ForeignKey.to_field 976 977 The field on the related object that the relation is to. By default, Django 978 uses the primary key of the related object. 979 980.. versionadded:: 1.3 981 982.. attribute:: ForeignKey.on_delete 983 984 When an object referenced by a :class:`ForeignKey` is deleted, Django by 985 default emulates the behavior of the SQL constraint ``ON DELETE CASCADE`` 986 and also deletes the object containing the ``ForeignKey``. This behavior 987 can be overridden by specifying the :attr:`on_delete` argument. For 988 example, if you have a nullable :class:`ForeignKey` and you want it to be 989 set null when the referenced object is deleted:: 990 991 user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) 992 993 The possible values for :attr:`on_delete` are found in 994 :mod:`django.db.models`: 995 996 * :attr:`~django.db.models.CASCADE`: Cascade deletes; the default. 997 998 * :attr:`~django.db.models.PROTECT`: Prevent deletion of the referenced 999 object by raising :exc:`django.db.models.ProtectedError`, a subclass of 1000 :exc:`django.db.IntegrityError`. 1001 1002 * :attr:`~django.db.models.SET_NULL`: Set the :class:`ForeignKey` null; 1003 this is only possible if :attr:`null` is ``True``. 1004 1005 * :attr:`~django.db.models.SET_DEFAULT`: Set the :class:`ForeignKey` to its 1006 default value; a default for the :class:`ForeignKey` must be set. 1007 1008 * :func:`~django.db.models.SET()`: Set the :class:`ForeignKey` to the value 1009 passed to :func:`~django.db.models.SET()`, or if a callable is passed in, 1010 the result of calling it. In most cases, passing a callable will be 1011 necessary to avoid executing queries at the time your models.py is 1012 imported:: 1013 1014 def get_sentinel_user(): 1015 return User.objects.get_or_create(username='deleted')[0] 1016 1017 class MyModel(models.Model): 1018 user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) 1019 1020 * :attr:`~django.db.models.DO_NOTHING`: Take no action. If your database 1021 backend enforces referential integrity, this will cause an 1022 :exc:`~django.db.IntegrityError` unless you manually add a SQL ``ON 1023 DELETE`` constraint to the database field (perhaps using 1024 :ref:`initial sql<initial-sql>`). 1025 1026.. _ref-manytomany: 1027 1028``ManyToManyField`` 1029------------------- 1030 1031.. class:: ManyToManyField(othermodel, [**options]) 1032 1033A many-to-many relationship. Requires a positional argument: the class to which 1034the model is related. This works exactly the same as it does for 1035:class:`ForeignKey`, including all the options regarding :ref:`recursive 1036<recursive-relationships>` and :ref:`lazy <lazy-relationships>` relationships. 1037 1038Database Representation 1039~~~~~~~~~~~~~~~~~~~~~~~ 1040 1041Behind the scenes, Django creates an intermediary join table to 1042represent the many-to-many relationship. By default, this table name 1043is generated using the name of the many-to-many field and the model 1044that contains it. Since some databases don't support table names above 1045a certain length, these table names will be automatically truncated to 104664 characters and a uniqueness hash will be used. This means you might 1047see table names like ``author_books_9cdf4``; this is perfectly normal. 1048You can manually provide the name of the join table using the 1049:attr:`~ManyToManyField.db_table` option. 1050 1051.. _manytomany-arguments: 1052 1053Arguments 1054~~~~~~~~~ 1055 1056:class:`ManyToManyField` accepts an extra set of arguments -- all optional -- 1057that control how the relationship functions. 1058 1059.. attribute:: ManyToManyField.related_name 1060 1061 Same as :attr:`ForeignKey.related_name`. 1062 1063.. attribute:: ManyToManyField.limit_choices_to 1064 1065 Same as :attr:`ForeignKey.limit_choices_to`. 1066 1067 ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a 1068 custom intermediate table specified using the 1069 :attr:`~ManyToManyField.through` parameter. 1070 1071.. attribute:: ManyToManyField.symmetrical 1072 1073 Only used in the definition of ManyToManyFields on self. Consider the 1074 following model:: 1075 1076 class Person(models.Model): 1077 friends = models.ManyToManyField("self") 1078 1079 When Django processes this model, it identifies that it has a 1080 :class:`ManyToManyField` on itself, and as a result, it doesn't add a 1081 ``person_set`` attribute to the ``Person`` class. Instead, the 1082 :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am 1083 your friend, then you are my friend. 1084 1085 If you do not want symmetry in many-to-many relationships with ``self``, set 1086 :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to 1087 add the descriptor for the reverse relationship, allowing 1088 :class:`ManyToManyField` relationships to be non-symmetrical. 1089 1090.. attribute:: ManyToManyField.through 1091 1092 Django will automatically generate a table to manage many-to-many 1093 relationships. However, if you want to manually specify the intermediary 1094 table, you can use the :attr:`~ManyToManyField.through` option to specify 1095 the Django model that represents the intermediate table that you want to 1096 use. 1097 1098 The most common use for this option is when you want to associate 1099 :ref:`extra data with a many-to-many relationship 1100 <intermediary-manytomany>`. 1101 1102.. attribute:: ManyToManyField.db_table 1103 1104 The name of the table to create for storing the many-to-many data. If this 1105 is not provided, Django will assume a default name based upon the names of 1106 the two tables being joined. 1107 1108.. _ref-onetoone: 1109 1110``OneToOneField`` 1111----------------- 1112 1113.. class:: OneToOneField(othermodel, [parent_link=False, **options]) 1114 1115A one-to-one relationship. Conceptually, this is similar to a 1116:class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the 1117"reverse" side of the relation will directly return a single object. 1118 1119This is most useful as the primary key of a model which "extends" 1120another model in some way; :ref:`multi-table-inheritance` is 1121implemented by adding an implicit one-to-one relation from the child 1122model to the parent model, for example. 1123 1124One positional argument is required: the class to which the model will be 1125related. This works exactly the same as it does for :class:`ForeignKey`, 1126including all the options regarding :ref:`recursive <recursive-relationships>` 1127and :ref:`lazy <lazy-relationships>` relationships. 1128 1129.. _onetoone-arguments: 1130 1131Additionally, ``OneToOneField`` accepts all of the extra arguments 1132accepted by :class:`ForeignKey`, plus one extra argument: 1133 1134.. attribute:: OneToOneField.parent_link 1135 1136 When ``True`` and used in a model which inherits from another 1137 (concrete) model, indicates that this field should be used as the 1138 link back to the parent class, rather than the extra 1139 ``OneToOneField`` which would normally be implicitly created by 1140 subclassing.