Django

Code

Changeset 2799

Show
Ignore:
Timestamp:
04/30/06 23:22:37 (2 years ago)
Author:
adrian
Message:

magic-removal: Did some proofreading to docs/model-api.txt. Not yet done.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/magic-removal/docs/model-api.txt

    r2795 r2799  
    1111    * Each model is a Python class that subclasses ``django.db.models.Model``. 
    1212    * Each attribute of the model represents a database field. 
    13     * Model metadata (non-field information) goes in an inner class named ``Meta``. 
    14     * Metadata used for administration purposes goes into an inner class named ``Admin``. 
     13    * Model metadata (non-field information) goes in an inner class named 
     14      ``Meta``. 
     15    * Metadata used for Django's admin site goes into an inner class named 
     16      ``Admin``. 
     17    * With all of this, Django gives you an automatically-generated 
     18      database-access API, which is explained in the `Database API reference`_. 
    1519 
    1620A companion to this document is the `official repository of model examples`_. 
    1721 
    18 .. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/ 
    19  
    20 Field objects 
     22.. _Database API reference: http://www.djangoproject.com/documentation/db_api/ 
     23.. _official repository of model examples: http://www.djangoproject.com/documentation/models/ 
     24 
     25Quick example 
    2126============= 
    2227 
    23 The most important part of a model is the list of database fields it defines. 
    24 Fields are defined by class attributes. 
    25  
    26 In this example, there are two fields, ``first_name`` and ``last_name`` :: 
     28This example model defines a ``Person``, which has a ``first_name`` and 
     29``last_name``:: 
     30 
     31    from django.db import models 
    2732 
    2833    class Person(models.Model): 
     
    3035        last_name = models.CharField(maxlength=30) 
    3136 
    32 Django will use ``first_name`` and ``last_name`` as the database column names. 
    33  
    34 Each field type, except for ``ForeignKey``, ``ManyToManyField`` and 
    35 ``OneToOneField``, takes an optional first positional argument -- a 
    36 human-readable name. If the human-readable name isn't given, Django will 
    37 automatically create the human-readable name by using the machine-readable 
    38 name, converting underscores to spaces. 
    39  
    40 In this example, the human-readable name is ``"Person's first name"``:: 
    41  
    42     first_name = models.CharField("Person's first name", maxlength=30) 
    43  
    44 In this example, the human-readable name is ``"first name"``:: 
    45  
    46     first_name = models.CharField(maxlength=30) 
    47  
    48 ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first 
    49 argument to be a model class, so use the ``verbose_name`` keyword argument to 
    50 specify the human-readable name:: 
    51  
    52     poll = models.ForeignKey(Poll, verbose_name="the related poll") 
    53     sites = models.ManyToManyField(Site, verbose_name="list of sites") 
    54     place = models.OneToOneField(Place, verbose_name="related place") 
    55  
    56 Convention is not to capitalize the first letter of the ``verbose_name``. 
    57 Django will automatically capitalize the first letter where it needs to. 
     37``first_name`` and ``last_name`` are *fields* of the model. Each field is 
     38specified as a class attribute, and each attribute maps to a database column. 
     39 
     40The above ``Person`` model would create an SQL table like this:: 
     41 
     42    CREATE TABLE myapp_person ( 
     43        "id" serial NOT NULL PRIMARY KEY, 
     44        "first_name" varchar(30) NOT NULL, 
     45        "last_name" varchar(30) NOT NULL 
     46    ); 
     47 
     48Three technical notes: 
     49 
     50    * The name of the table, ``myapp_person``, is automatically derived from 
     51      some model metadata but can be overridden. See _`Table names` below. 
     52    * An ``id`` field is added automatically, but this behavior can be 
     53      overriden. See _`Automatic primary key fields` below. 
     54    * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL 
     55      syntax, but it's worth noting Django uses SQL tailored to the database 
     56      backend specified in your `settings file`_. 
     57 
     58.. _settings file: http://www.djangoproject.com/documentation/settings/ 
     59 
     60Fields 
     61====== 
     62 
     63The most important part of a model -- and the only required part of a model -- 
     64is the list of database fields it defines. Fields are specified by class 
     65attributes. 
     66 
     67Example:: 
     68 
     69    class Musician(models.Model): 
     70        first_name = models.CharField(maxlength=50) 
     71        last_name = models.CharField(maxlength=50) 
     72        instrument = models.CharField(maxlength=100) 
     73 
     74    class Album(models.Model): 
     75        artist = models.ForeignKey(Musician) 
     76        name = models.CharField(maxlength=100) 
     77        release_date = models.DateField() 
     78        num_stars = models.IntegerField() 
    5879 
    5980Field name restrictions 
    6081----------------------- 
    6182 
    62 TODO: Fill this section. 
    63  
    64     * Can't be Python reserved word. 
    65     * Can't have more than one underscore in a row, due to query lookup. 
    66  
    67 General field options 
    68 --------------------- 
     83Django places only two restrictions on model field names: 
     84 
     85    1. A field name cannot be a Python reserved word, because that would result 
     86       in a Python syntax error. For example:: 
     87 
     88           class Example(models.Model): 
     89               pass = models.IntegerField() # 'pass' is a reserved word! 
     90 
     91    2. A field name cannot contain more than one underscore in a row, due to 
     92       the way Django's query lookup syntax works. For example:: 
     93 
     94           class Example(models.Model): 
     95               foo__bar = models.IntegerField() 'foo__bar' has two underscores! 
     96 
     97These limitations can be worked around, though, because your field name doesn't 
     98necessarily have to match your database column name. See `db_column`_ below. 
     99 
     100SQL reserved words, such as ``join``, ``where`` or ``select`, *are* allowed as 
     101model field names, because Django escapes all database table names and column 
     102names in every underlying SQL query. It uses the quoting syntax of your 
     103particular database engine. 
     104 
     105Field types 
     106----------- 
     107 
     108Each field in your model should be an instance of the appropriate ``Field`` 
     109class. Django uses the field class types to determine a few things: 
     110 
     111    * The database column type (e.g. ``INTEGER``, ``VARCHAR``). 
     112    * The widget to use in Django's admin interface, if you care to use it 
     113      (e.g. ``<input type="text">``, ``<select>``). 
     114    * The minimal validation requirements, used in Django's admin and in 
     115      manipulators. 
     116 
     117Here are all available field types: 
     118 
     119``AutoField`` 
     120~~~~~~~~~~~~~ 
     121 
     122An ``IntegerField`` that automatically increments according to available IDs. 
     123You usually won't need to use this directly; a primary key field will 
     124automatically be added to your model if you don't specify otherwise. See 
     125_`Automatic primary key fields`. 
     126 
     127``BooleanField`` 
     128~~~~~~~~~~~~~~~~ 
     129 
     130A true/false field. 
     131 
     132The admin represents this as a checkbox. 
     133 
     134``CharField`` 
     135~~~~~~~~~~~~~ 
     136 
     137A string field, for small- to large-sized strings. 
     138 
     139For large amounts of text, use ``TextField``. 
     140 
     141The admin represents this as an ``<input type="text">`` (a single-line input). 
     142 
     143``CharField`` has an extra required argument, ``maxlength``, the maximum length 
     144(in characters) of the field. The maxlength is enforced at the database level 
     145and in Django's validation. 
     146 
     147``CommaSeparatedIntegerField`` 
     148~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     149 
     150A field of integers separated by commas. As in ``CharField``, the ``maxlength`` 
     151argument is required. 
     152 
     153``DateField`` 
     154~~~~~~~~~~~~~ 
     155 
     156A date field. Has a few extra optional arguments: 
     157 
     158    ======================  =================================================== 
     159    Argument                Description 
     160    ======================  =================================================== 
     161    ``auto_now``            Automatically set the field to now every time the 
     162                            object is saved. Useful for "last-modified" 
     163                            timestamps. 
     164 
     165    ``auto_now_add``        Automatically set the field to now when the object 
     166                            is first created. Useful for creation of 
     167                            timestamps. 
     168    ======================  =================================================== 
     169 
     170The admin represents this as an ``<input type="text">`` with a JavaScript 
     171calendar and a shortcut for "Today." 
     172 
     173``DateTimeField`` 
     174~~~~~~~~~~~~~~~~~ 
     175 
     176A date and time field. Takes the same extra options as ``DateField``. 
     177 
     178The admin represents this as two ``<input type="text">`` fields, with 
     179JavaScript shortcuts. 
     180 
     181``EmailField`` 
     182~~~~~~~~~~~~~~ 
     183 
     184A ``CharField`` that checks that the value is a valid e-mail address. 
     185This doesn't accept ``maxlength``. 
     186 
     187``FileField`` 
     188~~~~~~~~~~~~~ 
     189 
     190A file-upload field. 
     191 
     192Has an extra required argument, ``upload_to``, a local filesystem path to 
     193which files should be upload. This path may contain `strftime formatting`_, 
     194which will be replaced by the date/time of the file upload (so that 
     195uploaded files don't fill up the given directory). 
     196 
     197The admin represents this as an ``<input type="file">`` (a file-upload widget). 
     198 
     199Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few 
     200steps: 
     201 
     202    1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the 
     203        full path to a directory where you'd like Django to store uploaded 
     204        files. (For performance, these files are not stored in the database.) 
     205        Define ``MEDIA_URL`` as the base public URL of that directory. Make 
     206        sure that this directory is writable by the Web server's user 
     207        account. 
     208 
     209    2. Add the ``FileField`` or ``ImageField`` to your model, making sure 
     210        to define the ``upload_to`` option to tell Django to which 
     211        subdirectory of ``MEDIA_ROOT`` it should upload files. 
     212 
     213    3. All that will be stored in your database is a path to the file 
     214        (relative to ``MEDIA_ROOT``). You'll must likely want to use the 
     215        convenience ``get_<fieldname>_url`` function provided by Django. For 
     216        example, if your ``ImageField`` is called ``mug_shot``, you can get 
     217        the absolute URL to your image in a template with ``{{ 
     218        object.get_mug_shot_url }}``. 
     219 
     220.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 
     221 
     222``FilePathField`` 
     223~~~~~~~~~~~~~~~~~ 
     224 
     225A field whose choices are limited to the filenames in a certain directory 
     226on the filesystem. Has three special arguments, of which the first is 
     227required: 
     228 
     229    ======================  =================================================== 
     230    Argument                Description 
     231    ======================  =================================================== 
     232    ``path``                Required. The absolute filesystem path to a 
     233                            directory from which this ``FilePathField`` should 
     234                            get its choices. Example: ``"/home/images"``. 
     235 
     236    ``match``               Optional. A regular expression, as a string, that 
     237                            ``FilePathField`` will use to filter filenames. 
     238                            Note that the regex will be applied to the 
     239                            base filename, not the full path. Example: 
     240                            ``"foo.*\.txt^"``, which will match a file called 
     241                            ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``. 
     242 
     243    ``recursive``           Optional. Either ``True`` or ``False``. Default is 
     244                            ``False``. Specifies whether all subdirectories of 
     245                            ``path`` should be included. 
     246    ======================  =================================================== 
     247 
     248Of course, these arguments can be used together. 
     249 
     250The one potential gotcha is that ``match`` applies to the base filename, 
     251not the full path. So, this example:: 
     252 
     253    FilePathField(path="/home/images", match="foo.*", recursive=True) 
     254 
     255...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif`` 
     256because the ``match`` applies to the base filename (``foo.gif`` and 
     257``bar.gif``). 
     258 
     259``FloatField`` 
     260~~~~~~~~~~~~~~ 
     261 
     262A floating-point number. Has two **required** arguments: 
     263 
     264    ======================  =================================================== 
     265    Argument                Description 
     266    ======================  =================================================== 
     267    ``max_digits``          The maximum number of digits allowed in the number. 
     268 
     269    ``decimal_places``      The number of decimal places to store with the 
     270                            number. 
     271    ======================  =================================================== 
     272 
     273For example, to store numbers up to 999 with a resolution of 2 decimal places, 
     274you'd use:: 
     275 
     276    models.FloatField(..., max_digits=5, decimal_places=2) 
     277 
     278And to store numbers up to approximately one billion with a resolution of 10 
     279decimal places:: 
     280 
     281    models.FloatField(..., max_digits=19, decimal_places=10) 
     282 
     283The admin represents this as an ``<input type="text">`` (a single-line input). 
     284 
     285``ImageField`` 
     286~~~~~~~~~~~~~~ 
     287 
     288Like ``FileField``, but validates that the uploaded object is a valid 
     289image. Has two extra optional arguments, ``height_field`` and 
     290``width_field``, which, if set, will be auto-populated with the height and 
     291width of the image each time a model instance is saved. 
     292 
     293Requires the `Python Imaging Library`_. 
     294 
     295.. _Python Imaging Library: http://www.pythonware.com/products/pil/ 
     296 
     297``IntegerField`` 
     298~~~~~~~~~~~~~~~~ 
     299 
     300An integer. 
     301 
     302The admin represents this as an ``<input type="text">`` (a single-line input). 
     303 
     304``IPAddressField`` 
     305~~~~~~~~~~~~~~~~~~ 
     306 
     307An IP address, in string format (i.e. "24.124.1.30"). 
     308 
     309The admin represents this as an ``<input type="text">`` (a single-line input). 
     310 
     311``NullBooleanField`` 
     312~~~~~~~~~~~~~~~~~~~~ 
     313 
     314Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this 
     315instead of a ``BooleanField`` with ``null=True``. 
     316 
     317The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices. 
     318 
     319``PhoneNumberField`` 
     320~~~~~~~~~~~~~~~~~~~~ 
     321 
     322A ``CharField`` that checks that the value is a valid U.S.A.-style phone 
     323number (in the format ``XXX-XXX-XXXX``). 
     324 
     325``PositiveIntegerField`` 
     326~~~~~~~~~~~~~~~~~~~~~~~~ 
     327 
     328Like an ``IntegerField``, but must be positive. 
     329 
     330``PositiveSmallIntegerField`` 
     331~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     332 
     333Like a ``PositiveIntegerField``, but only allows values under a certain 
     334(database-dependent) point. 
     335 
     336``SlugField`` 
     337~~~~~~~~~~~~~ 
     338 
     339"Slug" is a newspaper term. A slug is a short label for something, 
     340containing only letters, numbers, underscores or hyphens. They're generally 
     341used in URLs. 
     342 
     343In the Django development version, you can specify ``maxlength``. If 
     344``maxlength`` is not specified, Django will use a default length of 50. In 
     345previous Django versions, there's no way to override the length of 50. 
     346 
     347Implies ``db_index=True``. 
     348 
     349Accepts an extra option, ``prepopulate_from``, which is a list of fields 
     350from which to auto-populate the slug, via JavaScript, in the object's admin 
     351form:: 
     352 
     353    models.SlugField(prepopulate_from=("pre_name", "name")) 
     354 
     355``prepopulate_from`` doesn't accept DateTimeFields. 
     356 
     357The admin represents ``SlugField`` as an ``<input type="text">`` (a 
     358single-line input). 
     359 
     360``SmallIntegerField`` 
     361~~~~~~~~~~~~~~~~~~~~~ 
     362 
     363Like an ``IntegerField``, but only allows values under a certain 
     364(database-dependent) point. 
     365 
     366``TextField`` 
     367~~~~~~~~~~~~~ 
     368 
     369A large text field. 
     370 
     371The admin represents this as a ``<textarea>`` (a multi-line input). 
     372 
     373``TimeField`` 
     374~~~~~~~~~~~~~ 
     375 
     376A time. Accepts the same auto-population options as ``DateField`` and 
     377``DateTimeField``. 
     378 
     379The admin represents this as an ``<input type="text">`` with some 
     380JavaScript shortcuts. 
     381 
     382``URLField`` 
     383~~~~~~~~~~~~ 
     384 
     385A field for a URL. If the ``verify_exists`` option is ``True`` (default), 
     386the URL given will be checked for existence (i.e., the URL actually loads 
     387and doesn't give a 404 response). 
     388 
     389The admin represents this as an ``<input type="text">`` (a single-line input). 
     390 
     391``USStateField`` 
     392~~~~~~~~~~~~~~~~ 
     393 
     394A two-letter U.S. state abbreviation. 
     395 
     396The admin represents this as an ``<input type="text">`` (a single-line input). 
     397 
     398``XMLField`` 
     399~~~~~~~~~~~~ 
     400 
     401A ``TextField`` that checks that the value is valid XML that matches a 
     402given schema. Takes one required argument, ``schema_path``, which is the 
     403filesystem path to a RelaxNG_ schema against which to validate the field. 
     404 
     405.. _RelaxNG: http://www.relaxng.org/ 
     406 
     407Field options 
     408------------- 
    69409 
    70410The following arguments are available to all field types. All are optional. 
    71411 
    72412``null`` 
    73     If ``True``, Django will store empty values as ``NULL`` in the database. 
    74     Default is ``False``. 
    75  
    76     Note that empty string values will always get stored as empty strings, not 
    77     as ``NULL`` -- so use ``null=True`` for non-string fields such as integers, 
    78     booleans and dates. 
    79  
    80     Avoid using ``null`` on string-based fields such as ``CharField`` and 
    81     ``TextField`` unless you have an excellent reason. If a string-based field 
    82     has ``null=True``, that means it has two possible values for "no data": 
    83     ``NULL``, and the empty string. In most cases, it's redundant to have two 
    84     possible values for "no data;" Django convention is to use the empty 
    85     string, not ``NULL``. 
     413~~~~~~~~ 
     414 
     415If ``True``, Django will store empty values as ``NULL`` in the database. 
     416Default is ``False``. 
     417 
     418Note that empty string values will always get stored as empty strings, not 
     419as ``NULL`` -- so use ``null=True`` for non-string fields such as integers, 
     420booleans and dates. 
     421 
     422Avoid using ``null`` on string-based fields such as ``CharField`` and 
     423``TextField`` unless you have an excellent reason. If a string-based field 
     424has ``null=True``, that means it has two possible values for "no data": 
     425``NULL``, and the empty string. In most cases, it's redundant to have two 
     426possible values for "no data;" Django convention is to use the empty 
     427string, not ``NULL``. 
    86428 
    87429``blank`` 
    88     If ``True``, the field is allowed to be blank. 
    89  
    90     Note that this is different than ``null``. ``null`` is purely 
    91     database-related, whereas ``blank`` is validation-related. If a field has 
    92     ``blank=True``, validation on Django's admin site will allow entry of an 
    93     empty value. If a field has ``blank=False``, the field will be required. 
     430~~~~~~~~~ 
     431 
     432If ``True``, the field is allowed to be blank. 
     433 
     434Note that this is different than ``null``. ``null`` is purely 
     435database-related, whereas ``blank`` is validation-related. If a field has 
     436``blank=True``, validation on Django's admin site will allow entry of an 
     437empty value. If a field has ``blank=False``, the field will be required. 
    94438 
    95439``choices`` 
    96     A list of 2-tuples to use as choices for this field. 
    97  
    98     If this is given, Django's admin will use a select box instead of the 
    99     standard text field and will limit choices to the choices given. 
    100  
    101     A choices list looks like this:: 
    102  
    103         YEAR_IN_SCHOOL_CHOICES = ( 
    104             ('FR', 'Freshman'), 
    105             ('SO', 'Sophomore'), 
    106             ('JR', 'Junior'), 
    107             ('SR', 'Senior'), 
    108             ('GR', 'Graduate'), 
    109         ) 
    110  
    111     The first element in each tuple is the actual value to be stored. The 
    112     second element is the human-readable name for the option. 
    113  
    114     The choices list can be defined either as part of your model class:: 
    115  
    116         class Foo(models.Model): 
    117             GENDER_CHOICES = ( 
    118                 ('M', 'Male'), 
    119                 ('F', 'Female'), 
    120             ) 
    121             gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) 
    122  
    123     or outside your model class altogether:: 
    124  
     440~~~~~~~~~~~ 
     441 
     442A list of 2-tuples to use as choices for this field. 
     443 
     444If this is given, Django's admin will use a select box instead of the 
     445standard text field and will limit choices to the choices given. 
     446 
     447A choices list looks like this:: 
     448 
     449    YEAR_IN_SCHOOL_CHOICES = ( 
     450        ('FR', 'Freshman'), 
     451        ('SO', 'Sophomore'), 
     452        ('JR', 'Junior'), 
     453        ('SR', 'Senior'), 
     454        ('GR', 'Graduate'), 
     455    ) 
     456 
     457The first element in each tuple is the actual value to be stored. The 
     458second element is the human-readable name for the option. 
     459 
     460The choices list can be defined either as part of your model class:: 
     461 
     462    class Foo(models.Model): 
    125463        GENDER_CHOICES = ( 
    126464            ('M', 'Male'), 
    127465            ('F', 'Female'), 
    128466        ) 
    129         class Foo(models.Model): 
    130             gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) 
     467        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) 
     468 
     469or outside your model class altogether:: 
     470 
     471    GENDER_CHOICES = ( 
     472        ('M', 'Male'), 
     473        ('F', 'Female'), 
     474    ) 
     475    class Foo(models.Model): 
     476        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) 
    131477 
    132478``core`` 
    133     For objects that are edited inline to a related object. 
    134  
    135     In the Django admin, if all "core" fields in an inline-edited object are 
    136     cleared, the object will be deleted. 
    137  
    138     It is an error to have an inline-editable relation without at least one 
    139     ``core=True`` field. 
     479~~~~~~~~ 
     480 
     481For objects that are edited inline to a related object. 
     482 
     483In the Django admin, if all "core" fields in an inline-edited object are 
     484cleared, the object will be deleted. 
     485 
     486It is an error to have an inline-editable relation without at least one 
     487``core=True`` field. 
    140488 
    141489``db_column`` 
    142     The name of the database column to use for this field. If this isn't given, 
    143     Django will use the field's name. 
    144  
    145     If your database column name is an SQL reserved word, or contains 
    146     characters that aren't allowed in Python variable names -- notably, the 
    147     hyphen -- that's OK. Django quotes column and table names behind the 
    148     scenes. 
     490~~~~~~~~~~~~~ 
     491 
     492The name of the database column to use for this field. If this isn't given, 
     493Django will use the field's name. 
     494 
     495If your database column name is an SQL reserved word, or contains 
     496characters that aren't allowed in Python variable names -- notably, the 
     497hyphen -- that's OK. Django quotes column and table names behind the 
     498scenes. 
    149499 
    150500``db_index`` 
    151     If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX`` 
    152     statement for this field. 
     501~~~~~~~~~~~~ 
     502 
     503If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX`` 
     504statement for this field. 
    153505 
    154506``default`` 
    155     The default value for the field. 
     507~~~~~~~~~~~ 
     508 
     509The default value for the field. 
    156510 
    157511``editable`` 
    158     If ``False``, the field will not be editable in the admin. Default is  ``True``. 
     512~~~~~~~~~~~~ 
     513 
     514If ``False``, the field will not be editable in the admin. Default is  ``True``. 
    159515 
    160516``help_text`` 
    161     Extra "help" text to be displayed under the field on the object's admin 
    162     form. It's useful for documentation even if your object doesn't have an 
    163     admin form. 
     517~~~~~~~~~~~~~ 
     518 
     519Extra "help" text to be displayed under the field on the object's admin 
     520form. It's useful for documentation even if your object doesn't have an 
     521admin form. 
    164522 
    165523``primary_key`` 
    166     If ``True``, this field is the primary key for the model. 
    167  
    168     If you don't specify ``primary_key=True`` for any fields in your model, 
    169     Django will automatically add this field:: 
    170  
    171         id = models.AutoField('ID', primary_key=True) 
    172  
    173     Thus, you don't need to set ``primary_key=True`` on any of your fields 
    174     unless you want to override the default primary-key behavior. 
    175  
    176     ``primary_key=True`` implies ``blank=False``, ``null=False`` and 
    177     ``unique=True``. Only one primary key is allowed on an object. 
     524~~~~~~~~~~~~~~~ 
     525 
     526If ``True``, this field is the primary key for the model. 
     527 
     528If you don't specify ``primary_key=True`` for any fields in your model, 
     529Django will automatically add this field:: 
     530 
     531    id = models.AutoField('ID', primary_key=True) 
     532 
     533Thus, you don't need to set ``primary_key=True`` on any of your fields 
     534unless you want to override the default primary-key behavior. 
     535 
     536``primary_key=True`` implies ``blank=False``, ``null=False`` and 
     537``unique=True``. Only one primary key is allowed on an object. 
    178538 
    179539``radio_admin`` 
    180     By default, Django's admin uses a select-box interface (<select>) for 
    181     fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin`` 
    182     is set to ``True``, Django will use a radio-button interface instead. 
    183  
    184     Don't use this for a field unless it's a ``ForeignKey`` or has ``choices`` 
    185     set. 
     540~~~~~~~~~~~~~~~ 
     541 
     542By default, Django's admin uses a select-box interface (<select>) for 
     543fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin`` 
     544is set to ``True``, Django will use a radio-button interface instead. 
     545 
     546Don't use this for a field unless it's a ``ForeignKey`` or has ``choices`` 
     547set. 
    186548 
    187549``unique`` 
    188     If ``True``, this field must be unique throughout the table. 
    189  
    190     This is enforced at the database level and at the Django admin-form level. 
     550~~~~~~~~~~ 
     551 
     552If ``True``, this field must be unique throughout the table. 
     553 
     554This is enforced at the database level and at the Django admin-form level. 
    191555 
    192556``unique_for_date`` 
    193     Set this to the name of a ``DateField`` or ``DateTimeField`` to require 
    194     that this field be unique for the value of the date field. 
    195  
    196     For example, if you have a field ``title`` that has 
    197     ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of 
    198     two records with the same ``title`` and ``pub_date``. 
    199  
    200     This is enforced at the Django admin-form level but not at the database level. 
     557~~~~~~~~~~~~~~~~~~~ 
     558 
     559Set this to the name of a ``DateField`` or ``DateTimeField`` to require 
     560that this field be unique for the value of the date field. 
     561 
     562For example, if you have a field ``title`` that has 
     563``unique_for_date="pub_date"``, then Django wouldn't allow the entry of 
     564two records with the same ``title`` and ``pub_date``. 
     565 
     566This is enforced at the Django admin-form level but not at the database level. 
    201567 
    202568``unique_for_month`` 
    203     Like ``unique_for_date``, but requires the field to be unique with respect 
    204     to the month. 
     569~~~~~~~~~~~~~~~~~~~~ 
     570 
     571Like ``unique_for_date``, but requires the field to be unique with respect 
     572to the month. 
    205573 
    206574``unique_for_year`` 
    207     Like ``unique_for_date`` and ``unique_for_month``. 
     575~~~~~~~~~~~~~~~~~~~ 
     576 
     577Like ``unique_for_date`` and ``unique_for_month``. 
    208578 
    209579``validator_list`` 
    210     A list of extra validators to apply to the field. Each should be a callable 
    211     that takes the parameters ``field_data, all_data`` and raises 
    212     ``django.core.validators.ValidationError`` for errors. (See the 
    213     `validator docs`_.) 
    214  
    215     Django comes with quite a few validators. They're in ``django.core.validators``. 
     580~~~~~~~~~~~~~~~~~~ 
     581 
     582A list of extra validators to apply to the field. Each should be a callable 
     583that takes the parameters ``field_data, all_data`` and raises 
     584``django.core.validators.ValidationError`` for errors. (See the 
     585`validator docs`_.) 
     586 
     587Django comes with quite a few validators. They're in ``django.core.validators``. 
    216588 
    217589.. _validator docs: http://www.djangoproject.com/documentation/forms/#validators 
    218590 
    219 Field types 
    220 ----------- 
    221  
    222 Each field in your model should be an instance of the appropriate ``Field`` 
    223 class. Django uses the field class types to determine a few things: 
    224  
    225     * The database column type (e.g. ``INTEGER``, ``VARCHAR``). 
    226     * The widget to use in Django's admin (e.g. ``<input type="text">``, ``<select>``). 
    227     * The minimal validation requirements, used in Django's admin and in manipulators. 
    228  
    229 Here are all available field types: 
    230  
    231 ``AutoField`` 
    232     An ``IntegerField`` that automatically increments according to available 
    233     IDs. You usually won't need to use this directly; a primary key field will 
    234     automatically be added to your model if you don't specify otherwise. (See 
    235     ``primary_key`` in ``General field options`` above.) 
    236  
    237 ``BooleanField`` 
    238     A true/false field. 
    239  
    240     The admin represents this as a checkbox. 
    241  
    242 ``CharField`` 
    243     A string field, for small- to large-sized strings. 
    244  
    245     For large amounts of text, use ``TextField``. 
    246  
    247     The admin represents this as an ``<input type="text">`` (a single-line input). 
    248  
    249     ``CharField`` has an extra required argument, ``maxlength``, the maximum 
    250     length (in characters) of the field. The maxlength is enforced at the 
    251     database level and in Django's validation. 
    252  
    253 ``CommaSeparatedIntegerField`` 
    254     A field of integers separated by commas. As in ``CharField``, the 
    255     ``maxlength`` argument is required. 
    256  
    257 ``DateField`` 
    258     A date field. Has a few extra optional arguments: 
    259  
    260         ======================  =================================================== 
    261         Argument                Description 
    262         ======================  =================================================== 
    263         ``auto_now``            Automatically set the field to now every time the 
    264                                 object is saved. Useful for "last-modified" 
    265                                 timestamps. 
    266  
    267         ``auto_now_add``        Automatically set the field to now when the object 
    268                                 is first created. Useful for creation of 
    269                                 timestamps. 
    270         ======================  =================================================== 
    271  
    272     The admin represents this as an ``<input type="text">`` with a JavaScript 
    273     calendar and a shortcut for "Today." 
    274  
    275 ``DateTimeField`` 
    276     A date and time field. Takes the same extra options as ``DateField``. 
    277  
    278     The admin represents this as two ``<input type="text">`` fields, with 
    279     JavaScript shortcuts. 
    280  
    281 ``EmailField`` 
    282     A ``CharField`` that checks that the value is a valid e-mail address. 
    283     This doesn't accept ``maxlength``. 
    284  
    285 ``FileField`` 
    286     A file-upload field. 
    287  
    288     Has an extra required argument, ``upload_to``, a local filesystem path to 
    289     which files should be upload. This path may contain `strftime formatting`_, 
    290     which will be replaced by the date/time of the file upload (so that 
    291     uploaded files don't fill up the given directory). 
    292  
    293     The admin represents this as an ``<input type="file">`` (a file-upload widget). 
    294  
    295     Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few 
    296     steps: 
    297  
    298         1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the 
    299            full path to a directory where you'd like Django to store uploaded 
    300            files. (For performance, these files are not stored in the database.) 
    301            Define ``MEDIA_URL`` as the base public URL of that directory. Make 
    302            sure that this directory is writable by the Web server's user 
    303            account. 
    304  
    305         2. Add the ``FileField`` or ``ImageField`` to your model, making sure 
    306            to define the ``upload_to`` option to tell Django to which 
    307            subdirectory of ``MEDIA_ROOT`` it should upload files. 
    308  
    309         3. All that will be stored in your database is a path to the file 
    310            (relative to ``MEDIA_ROOT``). You'll must likely want to use the 
    311            convenience ``get_<fieldname>_url`` function provided by Django. For 
    312            example, if your ``ImageField`` is called ``mug_shot``, you can get 
    313            the absolute URL to your image in a template with ``{{ 
    314            object.get_mug_shot_url }}``. 
    315  
    316     .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 
    317  
    318 ``FilePathField`` 
    319     A field whose choices are limited to the filenames in a certain directory 
    320     on the filesystem. Has three special arguments, of which the first is 
    321     required: 
    322  
    323         ======================  =================================================== 
    324         Argument                Description 
    325         ======================  =================================================== 
    326         ``path``                Required. The absolute filesystem path to a 
    327                                 directory from which this ``FilePathField`` should 
    328                                 get its choices. Example: ``"/home/images"``. 
    329  
    330         ``match``               Optional. A regular expression, as a string, that 
    331                                 ``FilePathField`` will use to filter filenames. 
    332                                 Note that the regex will be applied to the 
    333                                 base filename, not the full path. Example: 
    334                                 ``"foo.*\.txt^"``, which will match a file called 
    335                                 ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``. 
    336  
    337         ``recursive``           Optional. Either ``True`` or ``False``. Default is 
    338                                 ``False``. Specifies whether all subdirectories of 
    339                                 ``path`` should be included. 
    340         ======================  =================================================== 
    341  
    342     Of course, these arguments can be used together. 
    343  
    344     The one potential gotcha is that ``match`` applies to the base filename, 
    345     not the full path. So, this example:: 
    346  
    347         FilePathField(path="/home/images", match="foo.*", recursive=True) 
    348  
    349     ...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif`` 
    350     because the ``match`` applies to the base filename (``foo.gif`` and 
    351     ``bar.gif``). 
    352  
    353 ``FloatField`` 
    354     A floating-point number. Has two **required** arguments: 
    355  
    356         ======================  =================================================== 
    357         Argument                Description 
    358         ======================  =================================================== 
    359         ``max_digits``          The maximum number of digits allowed in the number. 
    360  
    361         ``decimal_places``      The number of decimal places to store with the 
    362                                 number. 
    363         ======================  =================================================== 
    364  
    365     For example, to store numbers up to 999 with a resolution of 2 decimal places, 
    366     you'd use:: 
    367  
    368         models.FloatField(..., max_digits=5, decimal_places=2) 
    369  
    370     And to store numbers up to approximately one billion with a resolution of 10 
    371     decimal places:: 
    372  
    373         models.FloatField(..., max_digits=19, decimal_places=10) 
    374  
    375     The admin represents this as an ``<input type="text">`` (a single-line input). 
    376  
    377 ``ImageField`` 
    378     Like ``FileField``, but validates that the uploaded object is a valid 
    379     image. Has two extra optional arguments, ``height_field`` and 
    380     ``width_field``, which, if set, will be auto-populated with the height and 
    381     width of the image each time a model instance is saved. 
    382  
    383     Requires the `Python Imaging Library`_. 
    384  
    385     .. _Python Imaging Library: http://www.pythonware.com/products/pil/ 
    386  
    387 ``IntegerField`` 
    388     An integer. 
    389  
    390     The admin represents this as an ``<input type="text">`` (a single-line input). 
    391  
    392 ``IPAddressField`` 
    393     An IP address, in string format (i.e. "24.124.1.30"). 
    394  
    395     The admin represents this as an ``<input type="text">`` (a single-line input). 
    396  
    397 ``NullBooleanField`` 
    398     Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this 
    399     instead of a ``BooleanField`` with ``null=True``. 
    400  
    401     The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices. 
    402  
    403 ``PhoneNumberField`` 
    404     A ``CharField`` that checks that the value is a valid U.S.A.-style phone 
    405     number (in the format ``XXX-XXX-XXXX``). 
    406  
    407 ``PositiveIntegerField`` 
    408     Like an ``IntegerField``, but must be positive. 
    409  
    410 ``PositiveSmallIntegerField`` 
    411     Like a ``PositiveIntegerField``, but only allows values under a certain 
    412     (database-dependent) point. 
    413  
    414 ``SlugField`` 
    415     "Slug" is a newspaper term. A slug is a short label for something, 
    416     containing only letters, numbers, underscores or hyphens. They're generally 
    417     used in URLs. 
    418  
    419     In the Django development version, you can specify ``maxlength``. If 
    420     ``maxlength`` is not specified, Django will use a default length of 50. In 
    421     previous Django versions, there's no way to override the length of 50. 
    422  
    423     Implies ``db_index=True``. 
    424  
    425     Accepts an extra option, ``prepopulate_from``, which is a list of fields 
    426     from which to auto-populate the slug, via JavaScript, in the object's admin 
    427     form:: 
    428  
    429         models.SlugField(prepopulate_from=("pre_name", "name")) 
    430  
    431     ``prepopulate_from`` doesn't accept DateTimeFields. 
    432  
    433     The admin represents ``SlugField`` as an ``<input type="text">`` (a 
    434     single-line input). 
    435  
    436 ``SmallIntegerField`` 
    437     Like an ``IntegerField``, but only allows values under a certain 
    438     (database-dependent) point. 
    439  
    440 ``TextField`` 
    441     A large text field. 
    442  
    443     The admin represents this as a ``<textarea>`` (a multi-line input). 
    444  
    445 ``TimeField`` 
    446     A time. Accepts the same auto-population options as ``DateField`` and 
    447     ``DateTimeField``. 
    448  
    449     The admin represents this as an ``<input type="text">`` with some 
    450     JavaScript shortcuts. 
    451  
    452 ``URLField`` 
    453     A field for a URL. If the ``verify_exists`` option is ``True`` (default), 
    454     the URL given will be checked for existence (i.e., the URL actually loads 
    455     and doesn't give a 404 response). 
    456  
    457     The admin represents this as an ``<input type="text">`` (a single-line input). 
    458  
    459 ``USStateField`` 
    460     A two-letter U.S. state abbreviation. 
    461  
    462     The admin represents this as an ``<input type="text">`` (a single-line input). 
    463  
    464 ``XMLField`` 
    465     A ``TextField`` that checks that the value is valid XML that matches a 
    466     given schema. Takes one required argument, ``schema_path``, which is the 
    467     filesystem path to a RelaxNG_ schema against which to validate the field. 
    468  
    469     .. _RelaxNG: http://www.relaxng.org/ 
     591Verbose field names 
     592------------------- 
     593 
     594Each field type, except for ``ForeignKey``, ``ManyToManyField`` and 
     595``OneToOneField``, takes an optional first positional argument -- a 
     596verbose name. If the verbose name isn't given, Django will automatically create 
     597it using the field's attribute name, converting underscores to spaces. 
     598 
     599In this example, the verbose name is ``"Person's first name"``:: 
     600 
     601    first_name = models.CharField("Person's first name", maxlength=30) 
     602 
     603In this example, the verbose name is ``"first name"``:: 
     604 
     605    first_name = models.CharField(maxlength=30) 
     606 
     607``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first 
     608argument to be a model class, so use the ``verbose_name`` keyword argument:: 
     609 
     610    poll = models.ForeignKey(Poll, verbose_name="the related poll") 
     611    sites = models.ManyToManyField(Site, verbose_name="list of sites") 
     612    place = models.OneToOneField(Place, verbose_name="related place") 
     613 
     614Convention is not to capitalize the first letter of the ``verbose_name``. 
     615Django will automatically capitalize the first letter where it needs to. 
    470616 
    471617Relationships 
     
    497643 
    498644To create a recursive relationship -- an object that has a many-to-one 
    499 relationship with itself -- use ``models.ForeignKey("self")``. 
     645relationship with itself -- use ``models.ForeignKey('self')``. 
    500646 
    501647If you need to create a relationship on a model that has not yet been defined, 
     
    750896============ 
    751897 
    752 Give your model metadata by using an inner ``"class Meta"``, like so:: 
     898Give your model metadata by using an inner ``class Meta``, like so:: 
    753899 
    754900    class Foo(models.Model): 
    755901        bar = models.CharField(maxlength=30) 
    756         # ... 
     902 
    757903        class Meta: 
    758904            # ... 
    759905 
    760 Model metadata is "anything that's not a field" -- ordering options, etc. 
     906Model metadata is "anything that's not a field", such as ordering options, etc. 
    761907 
    762908Here's a list of all possible ``Meta`` options. No options are required. Adding 
     
    764910 
    765911``db_table`` 
    766     The name of the database table to use for the module:: 
    767  
    768         db_table = "pizza_orders" 
    769  
    770     If this isn't given, Django will use ``app_label + '_' + model_class_name``. 
    771  
    772     If your database table name is an SQL reserved word, or contains characters 
    773     that aren't allowed in Python variable names -- notably, the hyphen -- 
    774     that's OK. Django quotes column and table names behind the scenes. 
     912------------ 
     913 
     914The name of the database table to use for the module:: 
     915 
     916    db_table = "pizza_orders" 
     917 
     918If this isn't given, Django will use ``app_label + '_' + model_class_name``. 
     919 
     920If your database table name is an SQL reserved word, or contains characters 
     921that aren't allowed in Python variable names -- notably, the hyphen -- 
     922that's OK. Django quotes column and table names behind the scenes. 
    775923 
    776924``get_latest_by`` 
    777     The name of a ``DateField`` or ``DateTimeField``. If given, the module will 
    778     have a ``get_latest()`` function that fetches the "latest" object according 
    779     to that field:: 
    780  
    781         get_latest_by = "order_date" 
    782  
    783     See `Getting the "latest" object`_ for a full example. 
    784  
    785     .. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/ 
    786  
    787 ``module_name`` 
    788     The name of the module:: 
    789  
    790         module_name = "pizza_orders" 
    791  
    792     If this isn't given, Django will use a lowercase version of the class name. 
     925----------------- 
     926 
     927The name of a ``DateField`` or ``DateTimeField``. If given, the module will 
     928have a ``get_latest()`` function that fetches the "latest" object according 
     929to that field:: 
     930 
     931    get_latest_by = "order_date" 
     932 
     933See `Getting the "latest" object`_ for a full example. 
     934 
     935.. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/ 
    793936 
    794937``order_with_respect_to`` 
    795     Marks this object as "orderable" with respect to the given field. This is 
    796     almost always used with related objects to allow them to be ordered with 
    797     respect to a parent object. For example, if a ``PizzaToppping`` relates to 
    798     a ``Pizza`` object, you might use:: 
    799  
    800         order_with_respect_to = 'pizza' 
    801  
    802     to allow the toppings to be ordered with respect to the associated pizza. 
     938------------------------- 
     939 
     940Marks this object as "orderable" with respect to the given field. This is 
     941almost always used with related objects to allow them to be ordered with 
     942respect to a parent object. For example, if a ``PizzaToppping`` relates to 
     943a ``Pizza`` object, you might use:: 
     944 
     945    order_with_respect_to = 'pizza' 
     946 
     947...to allow the toppings to be ordered with respect to the associated pizza. 
    803948 
    804949``ordering`` 
    805     The default ordering for the object, for use when obtaining lists of objects:: 
    806  
    807         ordering = ['-order_date'] 
    808  
    809