This repository has been archived by the owner. It is now read-only.
Permalink
Newer
Older
100644 935 lines (668 sloc) 32.3 KB
1
======================================
2
Appendix A: Model Definition Reference
3
======================================
5
Chapter 5 explains the basics of defining models, and we use them throughout
6
the rest of the book. There is, however, a *huge* range of model options
7
available not covered elsewhere. This appendix explains each possible model
8
definition option.
10
Note that although these APIs are considered stable, the Django developers
11
consistently add new shortcuts and conveniences to the model definition. It's a
12
good idea to always check the latest documentation online at
13
http://docs.djangoproject.com/.
15
Fields
16
======
18
The most important part of a model -- and the only required part of a model --
19
is the list of database fields it defines.
20
21
.. admonition:: Field Name Restrictions
22
23
Django places only two restrictions on model field names:
24
25
1. A field name cannot be a Python reserved word, because that would result
26
in a Python syntax error. For example::
28
class Example(models.Model):
29
pass = models.IntegerField() # 'pass' is a reserved word!
31
2. A field name cannot contain more than one underscore in a row, due to
32
the way Django's query lookup syntax works. For example::
34
class Example(models.Model):
35
foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
36
37
These limitations can be worked around, though, because your field name
38
doesn't necessarily have to match your database column name. See
39
"db_column", below.
40
41
SQL reserved words, such as ``join``, ``where``, or ``select``, *are* allowed
42
as model field names, because Django escapes all database table names and
43
column names in every underlying SQL query. It uses the quoting syntax of your
44
particular database engine.
45
46
Each field in your model should be an instance of the appropriate ``Field``
47
class. Django uses the field class types to determine a few things:
48
49
* The database column type (e.g., ``INTEGER``, ``VARCHAR``).
50
51
* The widget to use in Django's forms and admin site, if you care to use it
52
(e.g., ``<input type="text">``, ``<select>``).
53
54
* The minimal validation requirements, which are used in Django's admin
55
interface and by forms.
57
A complete list of field classes follows, sorted alphabetically. Note that
58
relationship fields (``ForeignKey``, etc.) are handled in the next section.
60
AutoField
61
---------
63
An ``IntegerField`` that automatically increments according to available IDs.
64
You usually won't need to use this directly; a primary key field will
65
automatically be added to your model if you don't specify otherwise.
67
BooleanField
68
------------
70
A true/false field.
72
.. admonition:: MySQL users...
74
A boolean field in MySQL is stored as a ``TINYINT`` column with a value of
75
either 0 or 1 (most databases have a proper ``BOOLEAN`` type instead). So,
76
for MySQL, only, when a ``BooleanField`` is retrieved from the database
77
and stored on a model attribute, it will have the values 1 or 0, rather
78
than ``True`` or ``False``. Normally, this shouldn't be a problem, since
79
Python guarantees that ``1 == True`` and ``0 == False`` are both true.
80
Just be careful if you're writing something like ``obj is True`` when
81
``obj`` is a value from a boolean attribute on a model. If that model was
82
constructed using the ``mysql`` backend, the "``is``" test will fail.
83
Prefer an equality test (using "``==``") in cases like this.
85
CharField
86
---------
88
A string field, for small- to large-sized strings.
90
For very large amounts of text, use ``TextField``.
92
``CharField`` has one extra required argument: ``max_length``. This is the
93
maximum length (in characters) of the field. The ``max_length`` is enforced
94
at the database level and in Django's validation.
96
CommaSeparatedIntegerField
97
--------------------------
99
A field of integers separated by commas. As in ``CharField``, the
100
``max_length`` argument is required.
102
DateField
103
---------
105
A date, represented in Python by a ``datetime.date`` instance.
106
107
DateTimeField
108
-------------
109
110
A date and time, represented in Python by a ``datetime.datetime`` instance.
111
112
DecimalField
113
------------
114
115
A fixed-precision decimal number, represented in Python by a
116
``decimal.Decimal`` instance. Has two **required** arguments:
117
118
``max_digits``
119
The maximum number of digits allowed in the number
120
121
``decimal_places``
122
The number of decimal places to store with the number
123
124
For example, to store numbers up to 999 with a resolution of 2 decimal places,
125
you'd use::
126
127
models.DecimalField(..., max_digits=5, decimal_places=2)
128
129
And to store numbers up to approximately one billion with a resolution of 10
130
decimal places::
131
132
models.DecimalField(..., max_digits=19, decimal_places=10)
133
134
When assigning to a ``DecimalField``, use either a ``decimal.Decimal`` object
135
or a string -- not a Python float.
136
137
EmailField
138
----------
139
140
A ``CharField`` that checks that the value is a valid e-mail address.
141
142
FileField
143
---------
144
145
A file-upload field.
146
147
.. note::
148
The ``primary_key`` and ``unique`` arguments are not supported, and will
149
raise a ``TypeError`` if used.
150
151
Has one **required** argument:
152
153
``upload_to``
154
A local filesystem path that will be appended to your ``MEDIA_ROOT``
155
setting to determine the value of the ``django.core.files.File.url``
156
attribute.
157
158
This path may contain "strftime formatting" (see the Python docs for the
159
``time`` standard library module), which will be replaced using the
160
date/time of the file upload (so that uploaded files don't fill up the given
161
directory).
162
163
This may also be a callable, such as a function, which will be called to
164
obtain the upload path, including the filename. This callable must be able
165
to accept two arguments, and return a Unix-style path (with forward slashes)
166
to be passed along to the storage system. The two arguments that will be
167
passed are:
168
169
====================== ===============================================
170
Argument Description
171
====================== ===============================================
172
``instance`` An instance of the model where the
173
``FileField`` is defined. More specifically,
174
this is the particular instance where the
175
current file is being attached.
177
In most cases, this object will not have been
178
saved to the database yet, so if it uses the
179
default ``AutoField``, *it might not yet have a
180
value for its primary key field*.
182
``filename`` The filename that was originally given to the
183
file. This may or may not be taken into account
184
when determining the final destination path.
185
====================== ===============================================
186
187
Also has one optional argument:
188
189
``storage``
190
Optional. A storage object, which handles the storage and retrieval of your
191
files.
192
193
Using a ``FileField`` or an ``ImageField`` (see below) in a model
194
takes a few steps:
195
196
1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
197
full path to a directory where you'd like Django to store uploaded files.
198
(For performance, these files are not stored in the database.) Define
199
``MEDIA_URL`` as the base public URL of that directory. Make sure
200
that this directory is writable by the Web server's user account.
202
2. Add the ``FileField`` or ``ImageField`` to your model, making
203
sure to define the ``upload_to`` option to tell Django
204
to which subdirectory of ``MEDIA_ROOT`` it should upload files.
206
3. All that will be stored in your database is a path to the file
207
(relative to ``MEDIA_ROOT``). You'll most likely want to use the
208
convenience ``url`` function provided by
209
Django. For example, if your ``ImageField`` is called ``mug_shot``,
210
you can get the absolute URL to your image in a template with
211
``{{ object.mug_shot.url }}``.
212
213
For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and
214
``upload_to`` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
215
part of ``upload_to`` is strftime formatting; ``'%Y'`` is the
216
four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is the two-digit
217
day. If you upload a file on Jan. 15, 2007, it will be saved in the directory
218
``/home/media/photos/2007/01/15``.
219
220
If you want to retrieve the upload file's on-disk filename, or a URL that refers
221
to that file, or the file's size, you can use the
222
``name``, ``url`` and ``size`` attributes.
223
224
Note that whenever you deal with uploaded files, you should pay close attention
225
to where you're uploading them and what type of files they are, to avoid
226
security holes. *Validate all uploaded files* so that you're sure the files are
227
what you think they are. For example, if you blindly let somebody upload files,
228
without validation, to a directory that's within your Web server's document
229
root, then somebody could upload a CGI or PHP script and execute that script by
230
visiting its URL on your site. Don't allow that.
231
232
By default, ``FileField`` instances are
233
created as ``varchar(100)`` columns in your database. As with other fields, you
234
can change the maximum length using the ``max_length`` argument.
235
236
FilePathField
237
-------------
238
239
A ``CharField`` whose choices are limited to the filenames in a certain
240
directory on the filesystem. Has three special arguments, of which the first is
241
**required**:
242
243
``path``
244
Required. The absolute filesystem path to a directory from which this
245
``FilePathField`` should get its choices. Example: ``"/home/images"``.
246
247
``match``
248
Optional. A regular expression, as a string, that ``FilePathField``
249
will use to filter filenames. Note that the regex will be applied to the
250
base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
251
match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
252
253
``recursive``
254
Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
255
whether all subdirectories of ``path`` should be included.
256
257
Of course, these arguments can be used together.
258
259
The one potential gotcha is that ``match`` applies to the
260
base filename, not the full path. So, this example::
261
262
FilePathField(path="/home/images", match="foo.*", recursive=True)
263
264
...will match ``/home/images/bar/foo.gif`` but not ``/home/images/foo/bar.gif``
265
because the ``match`` applies to the base filename
266
(``foo.gif`` and ``bar.gif``).
267
268
By default, ``FilePathField`` instances are
269
created as ``varchar(100)`` columns in your database. As with other fields, you
270
can change the maximum length using the ``max_length`` argument.
271
272
FloatField
273
----------
274
275
A floating-point number represented in Python by a ``float`` instance.
276
277
ImageField
278
----------
279
280
Like ``FileField``, but validates that the uploaded object is a valid
281
image. Has two extra optional arguments:
282
283
``height_field``
284
Name of a model field which will be auto-populated with the height of the
285
image each time the model instance is saved.
286
287
``width_field``
288
Name of a model field which will be auto-populated with the width of the
289
image each time the model instance is saved.
290
291
In addition to the special attributes that are available for FileField``,
292
an ``ImageField`` also has ``height`` and ``width`` attributes, both of which
293
correspond to the image's height and width in pixels.
294
295
Requires the Python Imaging Library, available at http://www.pythonware.com/products/pil/.
296
297
By default, ``ImageField`` instances are
298
created as ``varchar(100)`` columns in your database. As with other fields, you
299
can change the maximum length using the ``max_length`` argument.
300
301
IntegerField
302
------------
303
304
An integer.
305
306
IPAddressField
307
--------------
308
309
An IP address, in string format (e.g. ``'192.0.2.30'``).
310
311
NullBooleanField
312
----------------
313
314
Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use
315
this instead of a ``BooleanField`` with ``null=True``.
316
317
PositiveIntegerField
318
--------------------
319
320
Like an ``IntegerField``, but must be positive.
321
322
PositiveSmallIntegerField
323
-------------------------
324
325
Like a ``PositiveIntegerField``, but only allows values under a certain
326
(database-dependent) point.
327
328
SlugField
329
---------
330
331
"Slug" is a newspaper term. A slug is a short label for something,
332
containing only letters, numbers, underscores or hyphens. They're generally used
333
in URLs.
334
335
Like a ``CharField``, you can specify ``max_length``. If ``max_length`` is not
336
specified, Django will use a default length of 50.
337
338
Implies setting ``db_index`` to ``True``.
339
340
SmallIntegerField
341
-----------------
342
343
Like an ``IntegerField``, but only allows values under a certain
344
(database-dependent) point.
345
346
TextField
347
---------
348
349
A large text field.
350
351
Also see ``CharField`` for storing smaller bits of text.
352
353
TimeField
354
---------
355
356
A time, represented in Python by a ``datetime.time`` instance. Accepts the same
357
auto-population options as ``DateField``.
358
359
URLField
360
--------
361
362
A ``CharField`` for a URL. Has one extra optional argument:
363
364
``verify_exists``
365
If ``True`` (the default), the URL given will be checked for existence
366
(i.e., the URL actually loads and doesn't give a 404 response). It should
367
be noted that when using the single-threaded development server, validating
368
a url being served by the same server will hang.
369
This should not be a problem for multithreaded servers.
370
371
Like all ``CharField`` subclasses, ``URLField`` takes the optional
372
``max_length`` argument. If you don't specify
373
``max_length``, a default of 200 is used.
374
375
XMLField
376
--------
377
378
A ``TextField`` that checks that the value is valid XML that matches a
379
given schema. Takes one required argument:
380
381
``schema_path``
382
The filesystem path to a RelaxNG schema against which to validate the
383
field. For more on RelaxNG, see http://www.relaxng.org/.
384
385
Universal Field Options
386
=======================
387
388
The following arguments are available to all field types. All are optional.
389
390
null
391
----
392
393
If ``True``, Django will store empty values as ``NULL`` in the database. If
394
``False``, saving empty values will likely result in a database error. Default
395
is ``False``.
396
397
Note that empty string values will always get stored as empty strings, not as
398
``NULL``. Only use ``null=True`` for non-string fields such as integers,
399
booleans and dates. For both types of fields, you will also need to set
400
``blank=True`` if you wish to permit empty values in forms, as the
401
``null`` parameter only affects database storage (see
402
``blank``).
403
404
Avoid using ``null`` on string-based fields such as
405
``CharField`` and ``TextField`` unless you have an excellent reason.
406
If a string-based field has ``null=True``, that means it has two possible values
407
for "no data": ``NULL``, and the empty string. In most cases, it's redundant to
408
have two possible values for "no data;" Django's convention is to use the empty
409
string, not ``NULL``.
410
411
.. note::
412
413
When using the Oracle database backend, the ``null=True`` option will be
414
coerced for string-based fields that have the empty string as a possible
415
value, and the value ``NULL`` will be stored to denote the empty string.
416
417
For more on this, see the section "Making Date and Numeric Fields Optional" in
418
Chapter 6.
419
420
blank
421
-----
423
If ``True``, the field is allowed to be blank. Default is ``False``.
425
Note that this is different than ``null``. ``null`` is
426
purely database-related, whereas ``blank`` is validation-related. If
427
a field has ``blank=True``, validation on Django's admin site will allow entry
428
of an empty value. If a field has ``blank=False``, the field will be required.
430
choices
431
-------
433
An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
434
field.
436
A choices list looks like this::
438
YEAR_IN_SCHOOL_CHOICES = (
439
('FR', 'Freshman'),
440
('SO', 'Sophomore'),
441
('JR', 'Junior'),
442
('SR', 'Senior'),
443
('GR', 'Graduate'),
444
)
446
The first element in each tuple is the actual value to be stored. The second
447
element is the human-readable name for the option.
449
The choices list can be defined either as part of your model class::
451
class Foo(models.Model):
452
GENDER_CHOICES = (
453
('M', 'Male'),
454
('F', 'Female'),
455
)
456
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
458
or outside your model class altogether::
460
GENDER_CHOICES = (
461
('M', 'Male'),
462
('F', 'Female'),
463
)
464
class Foo(models.Model):
465
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
467
You can also collect your available choices into named groups that can
468
be used for organizational purposes in a form::
470
MEDIA_CHOICES = (
471
('Audio', (
472
('vinyl', 'Vinyl'),
473
('cd', 'CD'),
474
)
475
),
476
('Video', (
477
('vhs', 'VHS Tape'),
478
('dvd', 'DVD'),
479
)
480
),
481
('unknown', 'Unknown'),
482
)
484
The first element in each tuple is the name to apply to the group. The
485
second element is an iterable of 2-tuples, with each 2-tuple containing
486
a value and a human-readable name for an option. Grouped options may be
487
combined with ungrouped options within a single list (such as the
488
`unknown` option in this example).
490
Finally, note that choices can be any iterable object -- not necessarily a list
491
or tuple. This lets you construct choices dynamically. But if you find yourself
492
hacking ``choices`` to be dynamic, you're probably better off using a
493
proper database table with a `ForeignKey``. ``choices`` is
494
meant for static data that doesn't change much, if ever.
496
db_column
497
---------
499
The name of the database column to use for this field. If this isn't given,
500
Django will use the field's name.
502
If your database column name is an SQL reserved word, or contains
503
characters that aren't allowed in Python variable names -- notably, the
504
hyphen -- that's OK. Django quotes column and table names behind the
505
scenes.
507
db_index
508
--------
510
If ``True``, ``django-admin.py sqlindexes`` will output a
511
``CREATE INDEX`` statement for this field.
513
db_tablespace
514
-------------
516
The name of the database tablespace to use for this field's index, if this field
517
is indexed. The default is the project's ``DEFAULT_INDEX_TABLESPACE``
518
setting, if set, or the ``db_tablespace`` of the model, if any. If
519
the backend doesn't support tablespaces, this option is ignored.
521
default
522
-------
523
524
The default value for the field. This can be a value or a callable object. If
525
callable it will be called every time a new object is created.
526
527
editable
528
--------
529
530
If ``False``, the field will not be editable in the admin or via forms
531
automatically generated from the model class. Default is ``True``.
532
533
help_text
534
---------
535
536
Extra "help" text to be displayed under the field on the object's admin form.
537
It's useful for documentation even if your object doesn't have an admin form.
538
539
Note that this value is *not* HTML-escaped when it's displayed in the admin
540
interface. This lets you include HTML in ``help_text`` if you so
541
desire. For example::
542
543
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
544
545
Alternatively you can use plain text and
546
``django.utils.html.escape()`` to escape any HTML special characters.
547
548
primary_key
549
-----------
550
551
If ``True``, this field is the primary key for the model.
552
553
If you don't specify ``primary_key=True`` for any fields in your model, Django
554
will automatically add an ``AutoField`` to hold the primary key, so you
555
don't need to set ``primary_key=True`` on any of your fields unless you want to
556
override the default primary-key behavior.
557
558
``primary_key=True`` implies ``null=False`` and ``unique=True``.
559
Only one primary key is allowed on an object.
560
561
unique
562
------
563
564
If ``True``, this field must be unique throughout the table.
565
566
This is enforced at the database level and at the level of forms created with
567
``ModelForm`` (including forms in the Django admin site). If
568
you try to save a model with a duplicate value in a ``unique``
569
field, an ``IntegrityError`` will be raised by the model's
570
``save`` method.
571
572
This option is valid on all field types except ``ManyToManyField``,
573
``FileField`` and ``ImageField``.
574
575
unique_for_date
576
---------------
577
578
Set this to the name of a ``DateField`` or ``DateTimeField`` to
579
require that this field be unique for the value of the date field.
580
581
For example, if you have a field ``title`` that has
582
``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
583
records with the same ``title`` and ``pub_date``.
584
585
This is enforced at the level of forms created with ``ModelForm`` (including
586
forms in the Django admin site) but not at the database level.
587
588
unique_for_month
589
----------------
590
591
Like ``unique_for_date``, but requires the field to be unique with
592
respect to the month.
593
594
unique_for_year
595
---------------
596
597
Like ``unique_for_date`` and ``unique_for_month``.
598
599
verbose_name
600
------------
601
602
A human-readable name for the field. If the verbose name isn't given, Django
603
will automatically create it using the field's attribute name, converting
604
underscores to spaces.
605
606
Relationships
607
=============
608
609
Clearly, the power of relational databases lies in relating tables to each
610
other. Django offers ways to define the three most common types of database
611
relationships: many-to-one, many-to-many, and one-to-one.
612
613
ForeignKey
614
----------
615
616
A many-to-one relationship. Requires a positional argument: the class to which
617
the model is related.
618
619
To create a recursive relationship -- an object that has a many-to-one
620
relationship with itself -- use ``models.ForeignKey('self')``.
621
622
If you need to create a relationship on a model that has not yet been defined,
623
you can use the name of the model, rather than the model object itself::
624
625
class Car(models.Model):
626
manufacturer = models.ForeignKey('Manufacturer')
627
# ...
628
629
class Manufacturer(models.Model):
630
# ...
631
632
Note, however, that this only refers to models in the same ``models.py`` file.
633
634
To refer to models defined in another
635
application, you must instead explicitly specify the application label. For
636
example, if the ``Manufacturer`` model above is defined in another application
637
called ``production``, you'd need to use::
638
639
class Car(models.Model):
640
manufacturer = models.ForeignKey('production.Manufacturer')
641
642
Behind the scenes, Django appends ``"_id"`` to the field name to create its
643
database column name. In the above example, the database table for the ``Car``
644
model will have a ``manufacturer_id`` column. (You can change this explicitly by
645
specifying ``db_column``) However, your code should never have to
646
deal with the database column name, unless you write custom SQL. You'll always
647
deal with the field names of your model object.
648
649
``ForeignKey`` accepts an extra set of arguments -- all optional -- that
650
define the details of how the relation works.
651
652
``limit_choices_to``
653
A dictionary of lookup arguments and values
654
that limit the available admin choices for this object. Use this with
655
functions from the Python ``datetime`` module to limit choices of objects by
656
date. For example::
657
658
limit_choices_to = {'pub_date__lte': datetime.now}
659
660
only allows the choice of related objects with a ``pub_date`` before the
661
current date/time to be chosen.
662
663
``limit_choices_to`` has no effect on the inline FormSets that are created
664
to display related objects in the admin.
665
666
``related_name``
667
The name to use for the relation from the related object back to this one.
668
669
``to_field``
670
The field on the related object that the relation is to. By default, Django
671
uses the primary key of the related object.
672
673
ManyToManyField
674
---------------
675
676
A many-to-many relationship. Requires a positional argument: the class to which
677
the model is related. This works exactly the same as it does for
678
``ForeignKey``, including all the options regarding recursive relationships
679
and lazy relationships.
680
681
Behind the scenes, Django creates an intermediary join table to represent the
682
many-to-many relationship. By default, this table name is generated using the
683
names of the two tables being joined. Since some databases don't support table
684
names above a certain length, these table names will be automatically
685
truncated to 64 characters and a uniqueness hash will be used. This means you
686
might see table names like ``author_books_9cdf4``; this is perfectly normal.
687
You can manually provide the name of the join table using the
688
``db_table`` option.
689
690
``ManyToManyField`` accepts an extra set of arguments -- all optional --
691
that control how the relationship functions.
692
693
``related_name``
694
Same as ``related_name`` in ``ForeignKey``.
695
696
``limit_choices_to``
697
Same as ``limit_choices_to`` in ``ForeignKey``.
698
699
``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
700
custom intermediate table specified using the
701
``through`` paramter.
702
703
``symmetrical``
704
Only used in the definition of ManyToManyFields on self. Consider the
705
following model::
706
707
class Person(models.Model):
708
friends = models.ManyToManyField("self")
709
710
When Django processes this model, it identifies that it has a
711
``ManyToManyField`` on itself, and as a result, it doesn't add a
712
``person_set`` attribute to the ``Person`` class. Instead, the
713
``ManyToManyField`` is assumed to be symmetrical -- that is, if I am
714
your friend, then you are my friend.
715
716
If you do not want symmetry in many-to-many relationships with ``self``, set
717
``symmetrical`` to ``False``. This will force Django to
718
add the descriptor for the reverse relationship, allowing
719
``ManyToManyField`` relationships to be non-symmetrical.
720
721
``through``
722
Django will automatically generate a table to manage many-to-many
723
relationships. However, if you want to manually specify the intermediary
724
table, you can use the ``through`` option to specify
725
the Django model that represents the intermediate table that you want to
726
use.
727
728
The most common use for this option is when you want to associate
729
extra data with a many-to-many relationship.
730
731
``db_table``
732
The name of the table to create for storing the many-to-many data. If this
733
is not provided, Django will assume a default name based upon the names of
734
the two tables being joined.
735
736
OneToOneField
737
-------------
738
739
A one-to-one relationship. Conceptually, this is similar to a
740
``ForeignKey`` with ``unique=True``, but the
741
"reverse" side of the relation will directly return a single object.
742
743
This is most useful as the primary key of a model which "extends"
744
another model in some way; multi-table-inheritance is
745
implemented by adding an implicit one-to-one relation from the child
746
model to the parent model, for example.
747
748
One positional argument is required: the class to which the model will be
749
related. This works exactly the same as it does for ``ForeignKey``,
750
including all the options regarding recursive relationships and lazy
751
relationships.
752
753
Additionally, ``OneToOneField`` accepts all of the extra arguments
754
accepted by ``ForeignKey``, plus one extra argument:
755
756
``parent_link``
757
When ``True`` and used in a model which inherits from another
758
(concrete) model, indicates that this field should be used as the
759
link back to the parent class, rather than the extra
760
``OneToOneField`` which would normally be implicitly created by
761
subclassing.
762
763
Model Metadata Options
764
======================
765
766
Model-specific metadata lives in a ``class Meta`` defined in the body of your
767
model class::
768
769
class Book(models.Model):
770
title = models.CharField(maxlength=100)
771
772
class Meta:
773
# model metadata options go here
774
...
775
776
Model metadata is "anything that's not a field," such as ordering options and so forth.
777
778
The sections that follow present a list of all possible ``Meta`` options.
779
No options are required. Adding ``class Meta`` to a model is completely optional.
780
781
abstract
782
--------
783
784
If ``True``, this model will be an abstract base class. See the Django
785
documentation for more on abstract base classes.
786
787
db_table
788
--------
789
790
The name of the database table to use for the model::
791
792
db_table = 'music_album'
793
794
Table names
795
~~~~~~~~~~~
796
797
To save you time, Django automatically derives the name of the database table
798
from the name of your model class and the app that contains it. A model's
799
database table name is constructed by joining the model's "app label" -- the
800
name you used in ``manage.py startapp`` -- to the model's class name, with an
801
underscore between them.
802
803
For example, if you have an app ``bookstore`` (as created by
804
``manage.py startapp bookstore``), a model defined as ``class Book`` will have
805
a database table named ``bookstore_book``.
806
807
To override the database table name, use the ``db_table`` parameter in
808
``class Meta``.
809
810
If your database table name is an SQL reserved word, or contains characters that
811
aren't allowed in Python variable names -- notably, the hyphen -- that's OK.
812
Django quotes column and table names behind the scenes.
813
814
db_tablespace
815
-------------
816
817
The name of the database tablespace to use for the model. If the backend doesn't
818
support tablespaces, this option is ignored.
819
820
get_latest_by
821
-------------
822
823
The name of a ``DateField`` or ``DateTimeField`` in the model. This
824
specifies the default field to use in your model ``Manager``'s
825
``latest`` method.
826
827
Example::
828
829
get_latest_by = "order_date"
830
831
managed
832
-------
833
834
Defaults to ``True``, meaning Django will create the appropriate database
835
tables in ``django-admin.py syncdb`` and remove them as part of a ``reset``
836
management command. That is, Django *manages* the database tables' lifecycles.
837
838
If ``False``, no database table creation or deletion operations will be
839
performed for this model. This is useful if the model represents an existing
840
table or a database view that has been created by some other means. This is
841
the *only* difference when ``managed`` is ``False``. All other aspects of
842
model handling are exactly the same as normal. This includes
843
844
1. Adding an automatic primary key field to the model if you don't declare
845
it. To avoid confusion for later code readers, it's recommended to
846
specify all the columns from the database table you are modeling when
847
using unmanaged models.
848
849
2. If a model with ``managed=False`` contains a
850
``ManyToManyField`` that points to another
851
unmanaged model, then the intermediary table for the many-to-many join
852
will also not be created. However, the intermediary table between one
853
managed and one unmanaged model *will* be created.
854
855
If you need to change this default behavior, create the intermediary
856
table as an explicit model (with ``managed`` set as needed) and use the
857
``through`` attribute to make the relation use your
858
custom model.
859
860
For tests involving models with ``managed=False``, it's up to you to ensure
861
the correct tables are created as part of the test setup.
862
863
If you're interested in changing the Python-level behavior of a model class,
864
you *could* use ``managed=False`` and create a copy of an existing model.
865
However, there's a better approach for that situation: proxy-models.
866
867
ordering
868
--------
869
870
The default ordering for the object, for use when obtaining lists of objects::
871
872
ordering = ['-order_date']
873
874
This is a tuple or list of strings. Each string is a field name with an optional
875
"-" prefix, which indicates descending order. Fields without a leading "-" will
876
be ordered ascending. Use the string "?" to order randomly.
877
878
.. note::
879
880
Regardless of how many fields are in ``ordering``, the admin
881
site uses only the first field.
882
883
For example, to order by a ``pub_date`` field ascending, use this::
884
885
ordering = ['pub_date']
886
887
To order by ``pub_date`` descending, use this::
888
889
ordering = ['-pub_date']
890
891
To order by ``pub_date`` descending, then by ``author`` ascending, use this::
892
893
ordering = ['-pub_date', 'author']
894
895
proxy
896
-----
897
898
If set to ``True``, a model which subclasses another model will be treated as
899
a proxy model. For more on proxy models, see the Django documentation.
900
901
unique_together
902
---------------
903
904
Sets of field names that, taken together, must be unique::
905
906
unique_together = (("driver", "restaurant"),)
907
908
This is a list of lists of fields that must be unique when considered together.
909
It's used by ``ModelForm`` forms (including forms in the Django admin site) and
910
is enforced at the database level (i.e., the appropriate ``UNIQUE`` statements
911
are included in the ``CREATE TABLE`` statement).
912
913
For convenience, unique_together can be a single sequence when dealing with a single
914
set of fields::
915
916
unique_together = ("driver", "restaurant")
917
918
verbose_name
919
------------
920
921
A human-readable name for the object, singular::
922
923
verbose_name = "pizza"
924
925
If this isn't given, Django will use a munged version of the class name:
926
``CamelCase`` becomes ``camel case``.
927
928
verbose_name_plural
929
-------------------
930
931
The plural name for the object::
932
933
verbose_name_plural = "stories"
934
Mar 26, 2013
935
If this isn't given, Django will use ``verbose_name`` + ``"s"``.