summaryrefslogtreecommitdiff
path: root/docs/model-api.txt
blob: 44253f301b14fac9c68209dd0751e86add06982c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
===============
Model reference
===============

A model is the single, definitive source of data about your data. It contains
the essential fields and behaviors of the data you're storing. Generally, each
model maps to a single database table.

The basics:

    * Each model is a Python class that subclasses ``django.db.models.Model``.
    * Each attribute of the model represents a database field.
    * Model metadata (non-field information) goes in an inner class named
      ``Meta``.
    * Metadata used for Django's admin site goes into an inner class named
      ``Admin``.
    * With all of this, Django gives you an automatically-generated
      database-access API, which is explained in the `Database API reference`_.

A companion to this document is the `official repository of model examples`_.

.. _Database API reference: http://www.djangoproject.com/documentation/db_api/
.. _official repository of model examples: http://www.djangoproject.com/documentation/models/

Quick example
=============

This example model defines a ``Person``, which has a ``first_name`` and
``last_name``::

    from django.db import models

    class Person(models.Model):
        first_name = models.CharField(maxlength=30)
        last_name = models.CharField(maxlength=30)

``first_name`` and ``last_name`` are *fields* of the model. Each field is
specified as a class attribute, and each attribute maps to a database column.

The above ``Person`` model would create an SQL table like this::

    CREATE TABLE myapp_person (
        "id" serial NOT NULL PRIMARY KEY,
        "first_name" varchar(30) NOT NULL,
        "last_name" varchar(30) NOT NULL
    );

Three technical notes:

    * The name of the table, ``myapp_person``, is automatically derived from
      some model metadata but can be overridden. See _`Table names` below.
    * An ``id`` field is added automatically, but this behavior can be
      overriden. See _`Automatic primary key fields` below.
    * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
      syntax, but it's worth noting Django uses SQL tailored to the database
      backend specified in your `settings file`_.

.. _settings file: http://www.djangoproject.com/documentation/settings/

Fields
======

The most important part of a model -- and the only required part of a model --
is the list of database fields it defines. Fields are specified by class
attributes.

Example::

    class Musician(models.Model):
        first_name = models.CharField(maxlength=50)
        last_name = models.CharField(maxlength=50)
        instrument = models.CharField(maxlength=100)

    class Album(models.Model):
        artist = models.ForeignKey(Musician)
        name = models.CharField(maxlength=100)
        release_date = models.DateField()
        num_stars = models.IntegerField()

Field name restrictions
-----------------------

Django places only two restrictions on model field names:

    1. A field name cannot be a Python reserved word, because that would result
       in a Python syntax error. For example::

           class Example(models.Model):
               pass = models.IntegerField() # 'pass' is a reserved word!

    2. A field name cannot contain more than one underscore in a row, due to
       the way Django's query lookup syntax works. For example::

           class Example(models.Model):
               foo__bar = models.IntegerField() 'foo__bar' has two underscores!

These limitations can be worked around, though, because your field name doesn't
necessarily have to match your database column name. See `db_column`_ below.

SQL reserved words, such as ``join``, ``where`` or ``select`, *are* allowed as
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.

Field types
-----------

Each field in your model should be an instance of the appropriate ``Field``
class. Django uses the field class types to determine a few things:

    * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
    * The widget to use in Django's admin interface, if you care to use it
      (e.g. ``<input type="text">``, ``<select>``).
    * The minimal validation requirements, used in Django's admin and in
      manipulators.

Here are all available field types:

``AutoField``
~~~~~~~~~~~~~

An ``IntegerField`` that automatically increments according to available IDs.
You usually won't need to use this directly; a primary key field will
automatically be added to your model if you don't specify otherwise. See
_`Automatic primary key fields`.

``BooleanField``
~~~~~~~~~~~~~~~~

A true/false field.

The admin represents this as a checkbox.

``CharField``
~~~~~~~~~~~~~

A string field, for small- to large-sized strings.

For large amounts of text, use ``TextField``.

The admin represents this as an ``<input type="text">`` (a single-line input).

``CharField`` has an extra required argument, ``maxlength``, the maximum length
(in characters) of the field. The maxlength is enforced at the database level
and in Django's validation.

``CommaSeparatedIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A field of integers separated by commas. As in ``CharField``, the ``maxlength``
argument is required.

``DateField``
~~~~~~~~~~~~~

A date field. Has a few extra optional arguments:

    ======================  ===================================================
    Argument                Description
    ======================  ===================================================
    ``auto_now``            Automatically set the field to now every time the
                            object is saved. Useful for "last-modified"
                            timestamps.

    ``auto_now_add``        Automatically set the field to now when the object
                            is first created. Useful for creation of
                            timestamps.
    ======================  ===================================================

The admin represents this as an ``<input type="text">`` with a JavaScript
calendar and a shortcut for "Today."

``DateTimeField``
~~~~~~~~~~~~~~~~~

A date and time field. Takes the same extra options as ``DateField``.

The admin represents this as two ``<input type="text">`` fields, with
JavaScript shortcuts.

``EmailField``
~~~~~~~~~~~~~~

A ``CharField`` that checks that the value is a valid e-mail address.
This doesn't accept ``maxlength``.

``FileField``
~~~~~~~~~~~~~

A file-upload field.

Has an extra required argument, ``upload_to``, a local filesystem path to
which files should be upload. This path may contain `strftime formatting`_,
which will be replaced by the date/time of the file upload (so that
uploaded files don't fill up the given directory).

The admin represents this as an ``<input type="file">`` (a file-upload widget).

Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few
steps:

    1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
        full path to a directory where you'd like Django to store uploaded
        files. (For performance, these files are not stored in the database.)
        Define ``MEDIA_URL`` as the base public URL of that directory. Make
        sure that this directory is writable by the Web server's user
        account.

    2. Add the ``FileField`` or ``ImageField`` to your model, making sure
        to define the ``upload_to`` option to tell Django to which
        subdirectory of ``MEDIA_ROOT`` it should upload files.

    3. All that will be stored in your database is a path to the file
        (relative to ``MEDIA_ROOT``). You'll must likely want to use the
        convenience ``get_<fieldname>_url`` function provided by Django. For
        example, if your ``ImageField`` is called ``mug_shot``, you can get
        the absolute URL to your image in a template with ``{{
        object.get_mug_shot_url }}``.

.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941

``FilePathField``
~~~~~~~~~~~~~~~~~

A field whose choices are limited to the filenames in a certain directory
on the filesystem. Has three special arguments, of which the first is
required:

    ======================  ===================================================
    Argument                Description
    ======================  ===================================================
    ``path``                Required. The absolute filesystem path to a
                            directory from which this ``FilePathField`` should
                            get its choices. Example: ``"/home/images"``.

    ``match``               Optional. A regular expression, as a string, that
                            ``FilePathField`` will use to filter filenames.
                            Note that the regex will be applied to the
                            base filename, not the full path. Example:
                            ``"foo.*\.txt^"``, which will match a file called
                            ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.

    ``recursive``           Optional. Either ``True`` or ``False``. Default is
                            ``False``. Specifies whether all subdirectories of
                            ``path`` should be included.
    ======================  ===================================================

Of course, these arguments can be used together.

The one potential gotcha is that ``match`` applies to the base filename,
not the full path. So, this example::

    FilePathField(path="/home/images", match="foo.*", recursive=True)

...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
because the ``match`` applies to the base filename (``foo.gif`` and
``bar.gif``).

``FloatField``
~~~~~~~~~~~~~~

A floating-point number. Has two **required** arguments:

    ======================  ===================================================
    Argument                Description
    ======================  ===================================================
    ``max_digits``          The maximum number of digits allowed in the number.

    ``decimal_places``      The number of decimal places to store with the
                            number.
    ======================  ===================================================

For example, to store numbers up to 999 with a resolution of 2 decimal places,
you'd use::

    models.FloatField(..., max_digits=5, decimal_places=2)

And to store numbers up to approximately one billion with a resolution of 10
decimal places::

    models.FloatField(..., max_digits=19, decimal_places=10)

The admin represents this as an ``<input type="text">`` (a single-line input).

``ImageField``
~~~~~~~~~~~~~~

Like ``FileField``, but validates that the uploaded object is a valid
image. Has two extra optional arguments, ``height_field`` and
``width_field``, which, if set, will be auto-populated with the height and
width of the image each time a model instance is saved.

Requires the `Python Imaging Library`_.

.. _Python Imaging Library: http://www.pythonware.com/products/pil/

``IntegerField``
~~~~~~~~~~~~~~~~

An integer.

The admin represents this as an ``<input type="text">`` (a single-line input).

``IPAddressField``
~~~~~~~~~~~~~~~~~~

An IP address, in string format (i.e. "24.124.1.30").

The admin represents this as an ``<input type="text">`` (a single-line input).

``NullBooleanField``
~~~~~~~~~~~~~~~~~~~~

Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this
instead of a ``BooleanField`` with ``null=True``.

The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.

``PhoneNumberField``
~~~~~~~~~~~~~~~~~~~~

A ``CharField`` that checks that the value is a valid U.S.A.-style phone
number (in the format ``XXX-XXX-XXXX``).

``PositiveIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~

Like an ``IntegerField``, but must be positive.

``PositiveSmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Like a ``PositiveIntegerField``, but only allows values under a certain
(database-dependent) point.

``SlugField``
~~~~~~~~~~~~~

"Slug" is a newspaper term. A slug is a short label for something,
containing only letters, numbers, underscores or hyphens. They're generally
used in URLs.

In the Django development version, you can specify ``maxlength``. If
``maxlength`` is not specified, Django will use a default length of 50. In
previous Django versions, there's no way to override the length of 50.

Implies ``db_index=True``.

Accepts an extra option, ``prepopulate_from``, which is a list of fields
from which to auto-populate the slug, via JavaScript, in the object's admin
form::

    models.SlugField(prepopulate_from=("pre_name", "name"))

``prepopulate_from`` doesn't accept DateTimeFields.

The admin represents ``SlugField`` as an ``<input type="text">`` (a
single-line input).

``SmallIntegerField``
~~~~~~~~~~~~~~~~~~~~~

Like an ``IntegerField``, but only allows values under a certain
(database-dependent) point.

``TextField``
~~~~~~~~~~~~~

A large text field.

The admin represents this as a ``<textarea>`` (a multi-line input).

``TimeField``
~~~~~~~~~~~~~

A time. Accepts the same auto-population options as ``DateField`` and
``DateTimeField``.

The admin represents this as an ``<input type="text">`` with some
JavaScript shortcuts.

``URLField``
~~~~~~~~~~~~

A field for a URL. If the ``verify_exists`` option is ``True`` (default),
the URL given will be checked for existence (i.e., the URL actually loads
and doesn't give a 404 response).

The admin represents this as an ``<input type="text">`` (a single-line input).

``USStateField``
~~~~~~~~~~~~~~~~

A two-letter U.S. state abbreviation.

The admin represents this as an ``<input type="text">`` (a single-line input).

``XMLField``
~~~~~~~~~~~~

A ``TextField`` that checks that the value is valid XML that matches a
given schema. Takes one required argument, ``schema_path``, which is the
filesystem path to a RelaxNG_ schema against which to validate the field.

.. _RelaxNG: http://www.relaxng.org/

Field options
-------------

The following arguments are available to all field types. All are optional.

``null``
~~~~~~~~

If ``True``, Django will store empty values as ``NULL`` in the database.
Default is ``False``.

Note that empty string values will always get stored as empty strings, not
as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
booleans and dates.

Avoid using ``null`` on string-based fields such as ``CharField`` and
``TextField`` unless you have an excellent reason. If a string-based field
has ``null=True``, that means it has two possible values for "no data":
``NULL``, and the empty string. In most cases, it's redundant to have two
possible values for "no data;" Django convention is to use the empty
string, not ``NULL``.

``blank``
~~~~~~~~~

If ``True``, the field is allowed to be blank.

Note that this is different than ``null``. ``null`` is purely
database-related, whereas ``blank`` is validation-related. If a field has
``blank=True``, validation on Django's admin site will allow entry of an
empty value. If a field has ``blank=False``, the field will be required.

``choices``
~~~~~~~~~~~

A list of 2-tuples to use as choices for this field.

If this is given, Django's admin will use a select box instead of the
standard text field and will limit choices to the choices given.

A choices list looks like this::

    YEAR_IN_SCHOOL_CHOICES = (
        ('FR', 'Freshman'),
        ('SO', 'Sophomore'),
        ('JR', 'Junior'),
        ('SR', 'Senior'),
        ('GR', 'Graduate'),
    )

The first element in each tuple is the actual value to be stored. The
second element is the human-readable name for the option.

The choices list can be defined either as part of your model class::

    class Foo(models.Model):
        GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)

or outside your model class altogether::

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    class Foo(models.Model):
        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)

``core``
~~~~~~~~

For objects that are edited inline to a related object.

In the Django admin, if all "core" fields in an inline-edited object are
cleared, the object will be deleted.

It is an error to have an inline-editable relation without at least one
``core=True`` field.

``db_column``
~~~~~~~~~~~~~

The name of the database column to use for this field. If this isn't given,
Django will use the field's name.

If your database column name is an SQL reserved word, or contains
characters that aren't allowed in Python variable names -- notably, the
hyphen -- that's OK. Django quotes column and table names behind the
scenes.

``db_index``
~~~~~~~~~~~~

If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
statement for this field.

``default``
~~~~~~~~~~~

The default value for the field.

``editable``
~~~~~~~~~~~~

If ``False``, the field will not be editable in the admin. Default is  ``True``.

``help_text``
~~~~~~~~~~~~~

Extra "help" text to be displayed under the field on the object's admin
form. It's useful for documentation even if your object doesn't have an
admin form.

``primary_key``
~~~~~~~~~~~~~~~

If ``True``, this field is the primary key for the model.

If you don't specify ``primary_key=True`` for any fields in your model,
Django will automatically add this field::

    id = models.AutoField('ID', primary_key=True)

Thus, you don't need to set ``primary_key=True`` on any of your fields
unless you want to override the default primary-key behavior.

``primary_key=True`` implies ``blank=False``, ``null=False`` and
``unique=True``. Only one primary key is allowed on an object.

``radio_admin``
~~~~~~~~~~~~~~~

By default, Django's admin uses a select-box interface (<select>) for
fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
is set to ``True``, Django will use a radio-button interface instead.

Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
set.

``unique``
~~~~~~~~~~

If ``True``, this field must be unique throughout the table.

This is enforced at the database level and at the Django admin-form level.

``unique_for_date``
~~~~~~~~~~~~~~~~~~~

Set this to the name of a ``DateField`` or ``DateTimeField`` to require
that this field be unique for the value of the date field.

For example, if you have a field ``title`` that has
``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
two records with the same ``title`` and ``pub_date``.

This is enforced at the Django admin-form level but not at the database level.

``unique_for_month``
~~~~~~~~~~~~~~~~~~~~

Like ``unique_for_date``, but requires the field to be unique with respect
to the month.

``unique_for_year``
~~~~~~~~~~~~~~~~~~~

Like ``unique_for_date`` and ``unique_for_month``.

``validator_list``
~~~~~~~~~~~~~~~~~~

A list of extra validators to apply to the field. Each should be a callable
that takes the parameters ``field_data, all_data`` and raises
``django.core.validators.ValidationError`` for errors. (See the
`validator docs`_.)

Django comes with quite a few validators. They're in ``django.core.validators``.

.. _validator docs: http://www.djangoproject.com/documentation/forms/#validators

Verbose field names
-------------------

Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
``OneToOneField``, takes an optional first positional argument -- a
verbose name. If the verbose name isn't given, Django will automatically create
it using the field's attribute name, converting underscores to spaces.

In this example, the verbose name is ``"Person's first name"``::

    first_name = models.CharField("Person's first name", maxlength=30)

In this example, the verbose name is ``"first name"``::

    first_name = models.CharField(maxlength=30)

``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
argument to be a model class, so use the ``verbose_name`` keyword argument::

    poll = models.ForeignKey(Poll, verbose_name="the related poll")
    sites = models.ManyToManyField(Site, verbose_name="list of sites")
    place = models.OneToOneField(Place, verbose_name="related place")

Convention is not to capitalize the first letter of the ``verbose_name``.
Django will automatically capitalize the first letter where it needs to.

Relationships
-------------

Clearly, the power of relational databases lies in relating tables to each
other. Django offers ways to define the three most common types of database
relationships: Many-to-one, many-to-many and one-to-one.

Many-to-one relationships
~~~~~~~~~~~~~~~~~~~~~~~~~

To define a many-to-one relationship, use ``ForeignKey``. You use it just like
any other ``Field`` type: by including it as a class attribute of your model.

``ForeignKey`` requires a positional argument: The class to which the model is
related.

For example, if a ``Place`` model is in a ``City`` -- that is, a ``City``
contains multiple places but each ``Place`` is only in one ``City`` -- use the
following definitions::

    class City(models.Model):
        # ...

    class Place(models.Model):
        # ...
        city = models.ForeignKey(City)

To create a recursive relationship -- an object that has a many-to-one
relationship with itself -- use ``models.ForeignKey('self')``.

If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::

    class Place(models.Model):
        # ...
        city = models.ForeignKey("City")

    class City(models.Model):
        # ...

The name of a ``ForeignKey`` (``city`` in the example above) generally should
be the name of the model, in singular form. Behind the scenes, Django appends
"_id" to the field name to create its database column name. However, your code
should never have to deal with the database column name, unless you write
custom SQL.

See the `Many-to-one relationship model example`_ for a full example.

.. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/

``ForeignKey`` fields take a number of extra arguments for defining how the
relationship should work. All are optional:

    =======================  ============================================================
    Argument                 Description
    =======================  ============================================================
    ``edit_inline``          If not ``False``, this related object is edited
                             "inline" on the related object's page. This means
                             that the object will not have its own admin
                             interface. Use either ``models.TABULAR`` or ``models.STACKED``,
                             which, respectively, designate whether the inline-editable
                             objects are displayed as a table or as a "stack" of
                             fieldsets.

    ``limit_choices_to``     A dictionary of lookup arguments and values (see
                             the `Database API reference`_) that limit the
                             available admin choices for this object. Use this
                             with ``models.LazyDate`` to limit choices of objects
                             by date. For example::

                                limit_choices_to = {'pub_date__lte' : models.LazyDate()}

                             only allows the choice of related objects with a
                             ``pub_date`` before the current date/time to be
                             chosen.

                             Not compatible with ``edit_inline``.

    ``max_num_in_admin``     For inline-edited objects, this is the maximum
                             number of related objects to display in the admin.
                             Thus, if a pizza could only have up to 10
                             toppings, ``max_num_in_admin=10`` would ensure
                             that a user never enters more than 10 toppings.

                             Note that this doesn't ensure more than 10 related
                             toppings ever get created. It just controls the
                             interface.

    ``min_num_in_admin``     The minimum number of related objects displayed in
                             the admin. Normally, at the creation stage,
                             ``num_in_admin`` inline objects are shown, and at
                             the edit stage ``num_extra_on_change`` blank
                             objects are shown in addition to all pre-existing
                             related objects.  However, no fewer than
                             ``min_num_in_admin`` related objects will ever be
                             displayed.

    ``num_extra_on_change``  The number of extra blank related-object fields to
                             show at the change stage.

    ``num_in_admin``         The default number of inline objects to display
                             on the object page at the add stage.

    ``raw_id_admin``         Only display a field for the integer to be entered
                             instead of a drop-down menu. This is useful when
                             related to an object type that will have too many
                             rows to make a select box practical.

                             Not used with ``edit_inline``.

    ``related_name``         The name to use for the relation from the related
                             object back to this one.  For example, when if
                             ``Topping`` has this field::

                                    models.ForeignKey(Pizza)

                             the ``related_name`` will be "topping_set" (taken from
                             the class name), which will in turn give ``Pizza``
                             a ``topping_set`` Object Set Descriptor.

                             If you instead were to use::

                                    models.ForeignKey(Pizza, related_name="munchies")

                             then the Object Set Descriptor on ``Topping`` would
                             be called ``munchies``.

                             This is only really useful when you have a single
                             object that relates to the same object more than
                             once.  For example, if a ``Story`` object has both
                             ``primary_category`` and ``secondary_category``
                             fields, to make sure that the ``Category`` objects
                             have the correct methods, you'd use fields like::

                                    models.ForeignKey(Category, related_name="primary_stories")
                                    models.ForeignKey(Category, related_name="secondary_stories")

                             ...which would give ``Category`` objects two Object Set
                             descriptors - one called ``primary_stories`` and one
                             called ``secondary_stories``.

    ``to_field``             The field on the related object that the relation
                             is to. By default, Django uses the primary key of
                             the related object.
    =======================  ============================================================

.. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/

Many-to-many relationships
~~~~~~~~~~~~~~~~~~~~~~~~~~

To define a many-to-many relationship, use ``ManyToManyField``. You use it just
like any other ``Field`` type: by including it as a class attribute of your
model.

``ManyToManyField`` requires a positional argument: The class to which the
model is related.

For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
here's how you'd represent that::

    class Topping(models.Model):
        # ...

    class Pizza(models.Model):
        # ...
        toppings = models.ManyToManyField(Topping)

As with ``ForeignKey``, a relationship to self can be defined by using the
string ``"self"`` instead of the model name; references to as-yet undefined
models can be made by using a string containing the model name.

The name of a ``ManyToManyField`` (``toppings`` in the example above) should
generally be a plural describing the set of related model objects.

Behind the scenes, Django creates an intermediary join table to represent the
many-to-many relationship.

It doesn't matter which model gets the ``ManyToManyField``, but you only need
it in one of the models -- not in both.

Generally, ``ManyToManyField`` instances should go in the object that's going
to be edited in the admin. In the above example, ``toppings`` is in ``Pizza``
(rather than ``Topping`` having a ``pizzas`` ``ManyToManyField`` ) because it's
more natural to think about a ``Pizza`` having toppings than a topping being on
multiple pizzas. The way it's set up above, the ``Pizza`` admin form would let
users select the toppings.

See the `Many-to-many relationship model example`_ for a full example.

.. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/

``ManyToManyField`` objects take a number of extra arguments for defining how
the relationship should work. All are optional:

    =======================  ============================================================
    Argument                 Description
    =======================  ============================================================
    ``related_name``         See the description of ``related_name`` in
                             ``ForeignKey`` above.

    ``filter_interface``     Use a nifty unobtrusive Javascript "filter" interface
                             instead of the usability-challenged ``<select multiple>``
                             in the admin form for this object. The value should be
                             ``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e.
                             should the interface be stacked horizontally or
                             vertically).

    ``limit_choices_to``     See the description under ``ForeignKey`` above.

    ``singular``             The singular name of the field.  Use to name the ``get_*``
                             methods: in the example above, Django gives the ``Pizza``
                             objects a ``get_topping_list()`` method, where ``topping``
                             is the default ``singular`` value derived from the lowercase
                             version of the class being linked to.  Use the singular
                             parameter to change this, which is if you want one model to
                             have multiple ``ManyToMany`` relationships to another model.

    ``symmetrical``          Only used in the definition of ManyToManyFields on self.
                             Consider the following model:

                             class Person(models.Model):
                                 friends = models.ManyToManyField("self")

                             When Django processes this model, it identifies that it has
                             a ManyToManyField on itself, and as a result, it doesn't add
                             a ``person_set`` attribute to the Person class. Instead, the
                             ManyToManyField is assumed to be symmetrical - that is, if
                             I am your friend, then you are my friend.

                             If you do not want symmetry in ManyToMany relationships with
                             self, set ``symmetrical`` to False. This will force Django to
                             add the descriptor for the reverse relationship, allow
                             ManyToMany relationships to be non-symmetrical.

    =======================  ============================================================

One-to-one relationships
~~~~~~~~~~~~~~~~~~~~~~~~

To define a one-to-one relationship, use ``OneToOneField``. You use it just
like any other ``Field`` type: by including it as a class attribute of your
model.

This is most useful on the primary key of an object when that object "extends"
another object in some way.

``OneToOneField`` requires a positional argument: The class to which the
model is related.

For example, if you're building a database of "places", you would build pretty
standard stuff such as address, phone number, etc. in the database. Then, if you
wanted to build a database of restaurants on top of the places, instead of
repeating yourself and replicating those fields in the ``Restaurant`` model, you
could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
restaurant "is-a" place).

As with ``ForeignKey``, a relationship to self can be defined by using the
string ``"self"`` instead of the model name; references to as-yet undefined
models can be made by using a string containing the model name.

This ``OneToOneField`` will actually replace the primary key ``id`` field
(since one-to-one relations share the same primary key), and will be displayed
as a read-only field when you edit an object in the admin interface:

See the `One-to-one relationship model example`_ for a full example.

.. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/

Meta options
============

Give your model metadata by using an inner ``class Meta``, like so::

    class Foo(models.Model):
        bar = models.CharField(maxlength=30)

        class Meta:
            # ...

Model metadata is "anything that's not a field", such as ordering options, etc.

Here's a list of all possible ``Meta`` options. No options are required. Adding
``class Meta`` to a model is completely optional.

``db_table``
------------

The name of the database table to use for the module::

    db_table = "pizza_orders"

If this isn't given, Django will use ``app_label + '_' + model_class_name``.

If your database table name is an SQL reserved word, or contains characters
that aren't allowed in Python variable names -- notably, the hyphen --
that's OK. Django quotes column and table names behind the scenes.

``get_latest_by``
-----------------

The name of a ``DateField`` or ``DateTimeField``. If given, the module will
have a ``get_latest()`` function that fetches the "latest" object according
to that field::

    get_latest_by = "order_date"

See `Getting the "latest" object`_ for a full example.

.. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/

``order_with_respect_to``
-------------------------

Marks this object as "orderable" with respect to the given field. This is
almost always used with related objects to allow them to be ordered with
respect to a parent object. For example, if a ``PizzaToppping`` relates to
a ``Pizza`` object, you might use::

    order_with_respect_to = 'pizza'

...to allow the toppings to be ordered with respect to the associated pizza.

``ordering``
------------

The default ordering for the object, for use when obtaining lists of objects::

    ordering = ['-order_date']

This is a tuple or list of strings. Each string is a field name with an
optional "-" prefix, which indicates descending order. Fields without a
leading "-" will be ordered ascending. Use the string "?" to order randomly.

For example, to order by a ``pub_date`` field ascending, use this::

    ordering = ['pub_date']

To order by ``pub_date`` descending, use this::

    ordering = ['-pub_date']

To order by ``pub_date`` descending, then by ``author`` ascending, use this::

    ordering = ['-pub_date', 'author']

See `Specifying ordering`_ for more examples.

Note that, regardless of how many fields are in ``ordering``, the admin
site uses only the first field.

.. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/

``permissions``
---------------

Extra permissions to enter into the permissions table when creating this
object. Add, delete and change permissions are automatically created for
each object that has ``admin`` set. This example specifies an extra
permission, ``can_deliver_pizzas``::

    permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)

This is a list or tuple of 2-tuples in the format
``(permission_code, human_readable_permission_name)``.

``unique_together``
-------------------

Sets of field names that, taken together, must be unique::

    unique_together = (("driver", "restaurant"),)

This is a list of lists of fields that must be unique when considered
together. It's used in the Django admin and is enforced at the database
level (i.e., the appropriate ``UNIQUE`` statements are included in the
``CREATE TABLE`` statement).

``verbose_name``
----------------

A human-readable name for the object, singular::

    verbose_name = "pizza"

If this isn't given, Django will use a munged version of the class name:
``CamelCase`` becomes ``camel case``.

``verbose_name_plural``
-----------------------

The plural name for the object::

    verbose_name_plural = "stories"

If this isn't given, Django will use ``verbose_name + "s"``.



========================================
THE REST OF THIS HAS NOT YET BEEN EDITED
========================================



Table names
===========

Automatic primary key fields
============================


Admin options
=============

If you want your model to be visible to the automatic Administration
system, your model must have an inner ``"class Admin"``, like so::

    class Foo(models.Model):
        bar = models.CharField(maxlength=30)
        # ...
        class Admin:
            # ...

The Admin class gives instructions to Django on how to display the Model
to the Administration system.

Here's a list of all possible ``Admin`` options. No options are required. Adding
``class Admin`` to a model is completely optional.

``date_hierarchy``
    To allow filtering of objects in the admin by date, set ``date_hierarchy``
    to the name of the field to filter by::

        date_hierarchy = 'order_date'

``fields``
    A list of fieldsets to display on the admin page.  Each fieldset is a 2-tuple:
    ``(name, field_options)``.  The ``name`` is a string to name the field set,
    and ``field_options`` is a dictionary of information about the fields to be
    displayed in that fieldset. This dictionary has the following keys:

        ``fields``
            A tuple of field names to display in this fieldset. To display
            multiple fields on the same line, wrap those fields in their
            own tuple.

            This key is required in the dictionary.

        ``classes``
            Extra CSS classes to apply to the fieldset. This is a simple
            string. You can apply multiple classes by separating them with
            spaces.

            Two useful classes defined by the default stylesheet are
            ``collapse`` and ``wide``.  Fieldsets with the ``collapse`` style
            will be initially collapsed in the admin and replaced with a small
            "click to expand" link.  Fieldsets with the ``wide`` style will be
            given extra horizontal space.

        ``description``
            Optional extra text to be displayed at the top of each fieldset,
            underneath the heading of the fieldset.  It is used verbatim,
            so you can use any HTML and you must escape any special HTML
            characters (such as ampersand) yourself.

    For example (taken from the ``django.contrib.flatpages`` model)::

        class Admin:
            ...
            fields = (
                (None, {
                    'fields': ('url', 'title', 'content', 'sites')
                }),
                ('Advanced options', {
                    'classes': 'collapse',
                    'fields' : ('enable_comments', 'registration_required', 'template_name')
                }),
            )

    results in an admin that looks like:

        .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png

    If ``fields`` isn't given Django will default to displaying each field that
    isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
    the same order as the fields are defined in the model.

``js``
    A list of strings representing URLs of JavaScript files to link into the
    admin screen. This can be used to tweak a given type of admin page in JS or
    to provide "quick links" to fill in default values for certain fields.

``list_display``
    List of fields to display on the list page in the admin.

    There are a few special cases that do other things besides displaying the
    contents of the given fields:

        * If the field given is a ``ForeignKey``, the ``repr()`` of the related
          object will be displayed.

        * ``ManyToManyField`` fields aren't supported, because that would
          entail executing a separate SQL statement for each row in the table.

        * If the field is a ``BooleanField``, a "on" or "off" icon will
          be displayed instead of ``True`` or ``False``.

        * If the field name is a method of the model, it'll be called, and the
          output will be displayed. This method should have a
          ``short_description`` function attribute, for use as the header for
          the field.

        * Use the string ``"__str__"`` to output the representation of the
          object, according to your model's ``__str__()`` function. If you
          don't define ``list_display``, Django will use the ``__str__`` by
          default.

    See the example below.

``list_filter``
    List of fields to filter by. Each field should either be a ``BooleanField``
    or else a field with a ``ManyToOne`` relation.

    Here's an example of how ``list_display`` and ``list_filter`` work (taken
    from the ``auth.user`` model)::

        class Admin:
            #...
            list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
            list_filter = ('is_staff', 'is_superuser')

    The above code results in an admin that looks like this:

        .. image:: http://media.djangoproject.com/img/doc/users_changelist.png

    (This example also has ``search_fields`` defined; see below).

``list_select_related``
    Either ``True`` or ``False``. Default is ``False``. If ``True``, the admin
    change list page will use the ``select_related`` database-API parameter in
    its query that retrieves the list of items.

    Note that Django will use ``select_related``, regardless of this setting,
    if one of the ``list_display`` fields is a ``ForeignKey``.

``ordering``
    A list or tuple (see the `Meta options`_, above) that gives a
    different ordering for the admin change list. If this isn't given, the
    model's default ordering will be used.

``save_as``
    Enables a "save as" feature on object pages.  Normally, objects have three
    save options: "Save", "Save and continue editing" and "Save and add
    another". If ``save_as`` is ``True``, "Save and add another" will be
    replaced by a "Save as" button.

    "Save as" means the object will be saved as a new object (with a new ID),
    rather than the old object.

``save_on_top``
    If this option is ``True``, object pages will have the save buttons across
    the top as well as at the bottom of the page.

``search_fields``
    A list of field names to provide a text search for. These fields should,
    obviously, be some kind of text field, such as ``CharField`` or
    ``TextField``.

Managers
========

The Manager is the interface through which database query operations
are provided to Django applications. At least one Manager exists for
every model in a Django application.

By default, Django will add a Manager with the name of ``objects`` to
every Django model. However, if you wish to use ``objects`` as a field
name, or if you wish to use a name other than ``objects`` for the Manager,
you can rename the Manager on a per-model basis. To rename the Manager
for a given class, define a class attribute of type models.Manager()
on that model. For example::

    from django.db import models

    class Person(models.Model):
        #...
        people = models.Manager()

In this example, ``Person.objects.all()`` will generate an error, but
``Person.people.all()`` will provide a list of all ``Person`` objects.

Managers can also be customized. This is achieved by extending the
base Manager class, and instantiating the new Manager on your model.
There are two reasons that you may want to customize a Manager: firstly,
to add utility methods to the Manager, and secondly, to modify the
initial Query Set provided by the Manager.

To modify the initial Query Set provided by a Manager, override the
``get_query_set()`` method to return a Query Set with the properties
you require. For example::

    class PersonManager(models.Manager):
        # Add some custom behavior to the Manager
        def move_house(self):
            # Some logic to help a person move house

        # Modify the initial Query Set provided by the manager
        def get_query_set(self):
            return super(Manager, self).get_query_set().filter(name__startswith="Fred")

    class Person(models.Model):
        #...
        objects = PersonManager()

In this example, ``Person.objects.all()`` will only return people whose name starts
with "Fred"; ``Person.objects.move_house()`` will also be available.

If required, you can add multiple Managers to a model. Every Manager attribute
added to a model can be accessed and used as a manager. This is an easy way
to define common filters types for your models. For example, the model::

    class MaleManager(models.Manager):
        def get_query_set(self):
            return super(Manager, self).get_query_set().filter(sex='M')

    class FemaleManager(models.Manager):
        def get_query_set(self):
            return super(Manager, self).get_query_set().filter(sex='F')

    class Person(models.Model):
        #...
        people = models.Manager()
        men = MaleManager()
        women = FemaleManager()

... will allow end users to request ``Person.men.all()``, ``Person.women.all()``,
and ``Person.people.all()``, yielding predictable results.

If you are going to install a customized Manager, be warned that the first
Manager that Django encounters in a model definition has special status.
Django interprets the first Manager defined in a class as the default Manager.
Certain operations use the default Manager to obtain lists of objects, so it
is generally a good idea for the first Manager to be relatively unfiltered.
In the last example, ``people`` is defined first - so the default Manager
will include everyone.

Model methods
=============

There are a number of methods you can define on model objects to control the
object's behavior.  First, any methods you define will be available as methods
of object instances. For example::

    class Pizza(models.Model):
        # ...

        def is_disgusting(self):
            return "anchovies" in [topping.name for topping in self.toppings.all()]

Now, every ``Pizza`` object will have a ``is_disgusting()`` method.

Note that the scope of custom methods is modified to be the same as the module
scope. These methods do NOT have access to globals within your model's module.
Additionally, custom methods have access to a few commonly-used objects for
convenience:

    * The ``datetime`` module from Python's standard library.
    * The ``db`` object from ``django.core.db``. This represents the database
      connection, so you can do custom queries via a cursor object. See
      "Executing custom SQL" below.

See `Giving models custom methods`_ for a full example.

.. _Giving models custom methods: http://www.djangoproject.com/documentation/models/custom_methods/

A few object methods have special meaning:

``__str__``
    Django uses ``str(obj)`` in a number of places, most notably as the value
    inserted into a template when it displays an object. Thus, you should always
    return a nice, human-readable string for the object's ``__str__``.

    Although defining ``__str__()`` isn't required, it's strongly encouraged.

    See `Adding str`_ for a full example.

    .. _Adding str: http://www.djangoproject.com/documentation/models/repr/

``get_absolute_url``
    Define a ``get_absolute_url`` method to tell Django how to calculate the
    URL for an object. For example::

        def get_absolute_url(self):
            return "/pizzas/%i/" % self.id

    Django uses this in its admin interface. If an object defines
    ``get_absolute_url``, the object detail page will have a "View on site"
    link that will jump you directly to the object's public view.

    It's good practice to use ``get_absolute_url()`` in templates, instead of
    hard-coding your objects' URLs.

Module-level methods
--------------------

If you want to add a method to the Model, rather than instances of the model,
you can use the Python ``staticmethod`` and ``classmethod`` operators. For
example::

    class Pizza(models.Model):
        # ...

        def get_pizzas_to_deliver():
            return get_list(delivered__exact=False)
        get_pizzas_to_deliver = staticmethod(get_pizzas_to_deliver)

Or, using Python 2.4 decorators::

    # ...
    @staticmethod
    def get_pizzas_to_deliver():
        # ...

This will make the top-level ``pizzas`` module have a ``get_pizzas_to_deliver()``
method::

    >>> from pizza_hut.models import Pizza
    >>> Pizza.get_pizzas_to_deliver()
    [ ... ]

Manipulator methods
-------------------

Similarly, you can add methods to the object's manipulators by defining methods
that being with "_manipulator_". This is most useful for providing custom
validators for certain fields, because manipulators automatically call any
method that begins with "validate"::

    class Pizza(models.Model):
        # ...

        def _manipulator_validate_customer_id(self, field_data, all_data):
            from django.core import validators
            from django.conf.settings import BAD_CUSTOMER_IDS

            if int(field_data) in BAD_CUSTOMER_IDS:
                raise validators.ValidationError, "We don't deliver to this customer."

Executing custom SQL
--------------------

Feel free to write custom SQL statements in custom model methods and
module-level methods. The object ``django.db.connection`` object represents
the current database connection. To use it, call ``connection.cursor()`` to
get a cursor object. Then, call ``cursor.execute(sql, [params])``
to execute the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return
the resulting rows. Example::

    def my_custom_sql(self):
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()
        return row

If your custom SQL statement alters the data in your database -- for example,
via a ``DELETE`` or ``UPDATE`` -- you'll need to call ``db.commit()``. Example::

    def my_custom_sql2(self):
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz])
        connection.commit()

``connection`` and ``cursor`` simply use the standard `Python DB-API`_. If you're not
familiar with the Python DB-API, note that the SQL statement in
``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters
directly within the SQL. If you use this technique, the underlying database
library will automatically add quotes and escaping to your parameter(s) as
necessary.

A final note: If all you want to do is a custom ``WHERE`` clause, you can just
just the ``where``, ``tables`` and ``params`` arguments to the standard lookup
API. See `Other lookup options`_.

.. _Python DB-API: http://www.python.org/peps/pep-0249.html
.. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables

Using models
============

Once you have created your model, you have to tell Django about your new application.
This is done by editing your settings file and adding the name of the module that
contains your models module to the ``INSTALLED_APPS`` tuple.

For example, if the models for your application are contained in the module
``project.myapp.models`` (the package structure that is created for an application
by the ``django-admin.py startapp`` script), ``INSTALLED_APPS`` should read, in part::

    INSTALLED_APPS = (
        #...
        project.myapp,
        #...
    )

Models across files
===================

It's perfectly OK to relate a model to one from another module. To do this,
just import the model module at the top of your model module. Then, just
refer to the other model class wherever needed. For example::

    from myproject.otherapp import Site

    class MyModel(models.Model):
        # ...
        sites = models.ManyToManyField(Site)