-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
/
fields.txt
2544 lines (1789 loc) · 93 KB
/
fields.txt
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
=====================
Model field reference
=====================
.. module:: django.db.models.fields
:synopsis: Built-in field types.
.. currentmodule:: django.db.models
This document contains all the API references of :class:`Field` including the
`field options`_ and `field types`_ Django offers.
.. seealso::
If the built-in fields don't do the trick, you can try `django-localflavor
<https://github.com/django/django-localflavor>`_ (`documentation
<https://django-localflavor.readthedocs.io/>`_), which contains assorted
pieces of code that are useful for particular countries and cultures.
Also, you can easily :doc:`write your own custom model fields
</howto/custom-model-fields>`.
.. note::
Technically, these models are defined in :mod:`django.db.models.fields`, but
for convenience they're imported into :mod:`django.db.models`; the standard
convention is to use ``from django.db import models`` and refer to fields as
``models.<Foo>Field``.
.. _common-model-field-options:
Field options
=============
The following arguments are available to all field types. All are optional.
``null``
--------
.. attribute:: Field.null
If ``True``, Django will store empty values as ``NULL`` in the database. Default
is ``False``.
Avoid using :attr:`~Field.null` on string-based fields such as
:class:`CharField` and :class:`TextField`. 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;" the Django convention is to use the empty string, not
``NULL``. One exception is when a :class:`CharField` has both ``unique=True``
and ``blank=True`` set. In this situation, ``null=True`` is required to avoid
unique constraint violations when saving multiple objects with blank values.
For both string-based and non-string-based fields, you will also need to
set ``blank=True`` if you wish to permit empty values in forms, as the
:attr:`~Field.null` parameter only affects database storage
(see :attr:`~Field.blank`).
.. note::
When using the Oracle database backend, the value ``NULL`` will be stored to
denote the empty string regardless of this attribute.
``blank``
---------
.. attribute:: Field.blank
If ``True``, the field is allowed to be blank. Default is ``False``.
Note that this is different than :attr:`~Field.null`. :attr:`~Field.null` is
purely database-related, whereas :attr:`~Field.blank` is validation-related. If
a field has ``blank=True``, form validation will allow entry of an empty value.
If a field has ``blank=False``, the field will be required.
.. admonition:: Supplying missing values
``blank=True`` can be used with fields having ``null=False``, but this will
require implementing :meth:`~django.db.models.Model.clean` on the model in
order to programmatically supply any missing values.
.. _field-choices:
``choices``
-----------
.. attribute:: Field.choices
A mapping or iterable in the format described below to use as choices for this
field. If choices are given, they're enforced by
:ref:`model validation <validating-objects>` and the default form widget will
be a select box with these choices instead of the standard text field.
If a mapping is given, the key element is the actual value to be set on the
model, and the second element is the human readable name. For example::
YEAR_IN_SCHOOL_CHOICES = {
"FR": "Freshman",
"SO": "Sophomore",
"JR": "Junior",
"SR": "Senior",
"GR": "Graduate",
}
You can also pass a :term:`sequence` consisting itself of iterables of exactly
two items (e.g. ``[(A1, B1), (A2, B2), …]``). The first element in each tuple
is the actual value to be set on the model, and the second element is the
human-readable name. For example::
YEAR_IN_SCHOOL_CHOICES = [
("FR", "Freshman"),
("SO", "Sophomore"),
("JR", "Junior"),
("SR", "Senior"),
("GR", "Graduate"),
]
``choices`` can also be defined as a callable that expects no arguments and
returns any of the formats described above. For example::
def get_currencies():
return {i: i for i in settings.CURRENCIES}
class Expense(models.Model):
amount = models.DecimalField(max_digits=10, decimal_places=2)
currency = models.CharField(max_length=3, choices=get_currencies)
Passing a callable for ``choices`` can be particularly handy when, for example,
the choices are:
* the result of I/O-bound operations (which could potentially be cached), such
as querying a table in the same or an external database, or accessing the
choices from a static file.
* a list that is mostly stable but could vary from time to time or from
project to project. Examples in this category are using third-party apps that
provide a well-known inventory of values, such as currencies, countries,
languages, time zones, etc.
.. versionchanged:: 5.0
Support for mappings and callables was added.
Generally, it's best to define choices inside a model class, and to
define a suitably-named constant for each value::
from django.db import models
class Student(models.Model):
FRESHMAN = "FR"
SOPHOMORE = "SO"
JUNIOR = "JR"
SENIOR = "SR"
GRADUATE = "GR"
YEAR_IN_SCHOOL_CHOICES = {
FRESHMAN: "Freshman",
SOPHOMORE: "Sophomore",
JUNIOR: "Junior",
SENIOR: "Senior",
GRADUATE: "Graduate",
}
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in {self.JUNIOR, self.SENIOR}
Though you can define a choices list outside of a model class and then
refer to it, defining the choices and names for each choice inside the
model class keeps all of that information with the class that uses it,
and helps reference the choices (e.g, ``Student.SOPHOMORE``
will work anywhere that the ``Student`` model has been imported).
.. _field-choices-named-groups:
You can also collect your available choices into named groups that can
be used for organizational purposes::
MEDIA_CHOICES = {
"Audio": {
"vinyl": "Vinyl",
"cd": "CD",
},
"Video": {
"vhs": "VHS Tape",
"dvd": "DVD",
},
"unknown": "Unknown",
}
The key of the mapping is the name to apply to the group and the value is the
choices inside that group, consisting of the field value and a human-readable
name for an option. Grouped options may be combined with ungrouped options
within a single mapping (such as the ``"unknown"`` option in this example).
You can also use a sequence, e.g. a list of 2-tuples::
MEDIA_CHOICES = [
(
"Audio",
(
("vinyl", "Vinyl"),
("cd", "CD"),
),
),
(
"Video",
(
("vhs", "VHS Tape"),
("dvd", "DVD"),
),
),
("unknown", "Unknown"),
]
Note that choices can be any sequence object -- not necessarily a list or
tuple. This lets you construct choices dynamically. But if you find yourself
hacking :attr:`~Field.choices` to be dynamic, you're probably better off using
a proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is
meant for static data that doesn't change much, if ever.
.. note::
A new migration is created each time the order of ``choices`` changes.
For each model field that has :attr:`~Field.choices` set, Django will normalize
the choices to a list of 2-tuples and add a method to retrieve the
human-readable name for the field's current value. See
:meth:`~django.db.models.Model.get_FOO_display` in the database API
documentation.
.. _field-choices-blank-label:
Unless :attr:`blank=False<Field.blank>` is set on the field along with a
:attr:`~Field.default` then a label containing ``"---------"`` will be rendered
with the select box. To override this behavior, add a tuple to ``choices``
containing ``None``; e.g. ``(None, 'Your String For Display')``.
Alternatively, you can use an empty string instead of ``None`` where this makes
sense - such as on a :class:`~django.db.models.CharField`.
.. _field-choices-enum-types:
Enumeration types
~~~~~~~~~~~~~~~~~
In addition, Django provides enumeration types that you can subclass to define
choices in a concise way::
from django.utils.translation import gettext_lazy as _
class Student(models.Model):
class YearInSchool(models.TextChoices):
FRESHMAN = "FR", _("Freshman")
SOPHOMORE = "SO", _("Sophomore")
JUNIOR = "JR", _("Junior")
SENIOR = "SR", _("Senior")
GRADUATE = "GR", _("Graduate")
year_in_school = models.CharField(
max_length=2,
choices=YearInSchool,
default=YearInSchool.FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in {
self.YearInSchool.JUNIOR,
self.YearInSchool.SENIOR,
}
These work similar to :mod:`enum` from Python's standard library, but with some
modifications:
* Enum member values are a tuple of arguments to use when constructing the
concrete data type. Django supports adding an extra string value to the end
of this tuple to be used as the human-readable name, or ``label``. The
``label`` can be a lazy translatable string. Thus, in most cases, the member
value will be a ``(value, label)`` 2-tuple. See below for :ref:`an example
of subclassing choices <field-choices-enum-subclassing>` using a more complex
data type. If a tuple is not provided, or the last item is not a (lazy)
string, the ``label`` is :ref:`automatically generated
<field-choices-enum-auto-label>` from the member name.
* A ``.label`` property is added on values, to return the human-readable name.
* A number of custom properties are added to the enumeration classes --
``.choices``, ``.labels``, ``.values``, and ``.names`` -- to make it easier
to access lists of those separate parts of the enumeration.
.. warning::
These property names cannot be used as member names as they would conflict.
* The use of :func:`enum.unique()` is enforced to ensure that values cannot be
defined multiple times. This is unlikely to be expected in choices for a
field.
Note that using ``YearInSchool.SENIOR``, ``YearInSchool['SENIOR']``, or
``YearInSchool('SR')`` to access or lookup enum members work as expected, as do
the ``.name`` and ``.value`` properties on the members.
.. _field-choices-enum-auto-label:
If you don't need to have the human-readable names translated, you can have
them inferred from the member name (replacing underscores with spaces and using
title-case):
.. code-block:: pycon
>>> class Vehicle(models.TextChoices):
... CAR = "C"
... TRUCK = "T"
... JET_SKI = "J"
...
>>> Vehicle.JET_SKI.label
'Jet Ski'
Since the case where the enum values need to be integers is extremely common,
Django provides an ``IntegerChoices`` class. For example::
class Card(models.Model):
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
suit = models.IntegerField(choices=Suit)
It is also possible to make use of the `Enum Functional API
<https://docs.python.org/3/howto/enum.html#functional-api>`_ with the caveat
that labels are automatically generated as highlighted above:
.. code-block:: pycon
>>> MedalType = models.TextChoices("MedalType", "GOLD SILVER BRONZE")
>>> MedalType.choices
[('GOLD', 'Gold'), ('SILVER', 'Silver'), ('BRONZE', 'Bronze')]
>>> Place = models.IntegerChoices("Place", "FIRST SECOND THIRD")
>>> Place.choices
[(1, 'First'), (2, 'Second'), (3, 'Third')]
.. _field-choices-enum-subclassing:
If you require support for a concrete data type other than ``int`` or ``str``,
you can subclass ``Choices`` and the required concrete data type, e.g.
:class:`~datetime.date` for use with :class:`~django.db.models.DateField`::
class MoonLandings(datetime.date, models.Choices):
APOLLO_11 = 1969, 7, 20, "Apollo 11 (Eagle)"
APOLLO_12 = 1969, 11, 19, "Apollo 12 (Intrepid)"
APOLLO_14 = 1971, 2, 5, "Apollo 14 (Antares)"
APOLLO_15 = 1971, 7, 30, "Apollo 15 (Falcon)"
APOLLO_16 = 1972, 4, 21, "Apollo 16 (Orion)"
APOLLO_17 = 1972, 12, 11, "Apollo 17 (Challenger)"
There are some additional caveats to be aware of:
- Enumeration types do not support :ref:`named groups
<field-choices-named-groups>`.
- Because an enumeration with a concrete data type requires all values to match
the type, overriding the :ref:`blank label <field-choices-blank-label>`
cannot be achieved by creating a member with a value of ``None``. Instead,
set the ``__empty__`` attribute on the class::
class Answer(models.IntegerChoices):
NO = 0, _("No")
YES = 1, _("Yes")
__empty__ = _("(Unknown)")
.. versionchanged:: 5.0
Support for using enumeration types directly in the ``choices`` was added.
``db_column``
-------------
.. attribute:: 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_comment``
--------------
.. attribute:: Field.db_comment
The comment on the database column to use for this field. It is useful for
documenting fields for individuals with direct database access who may not be
looking at your Django code. For example::
pub_date = models.DateTimeField(
db_comment="Date and time when the article was published",
)
``db_default``
--------------
.. versionadded:: 5.0
.. attribute:: Field.db_default
The database-computed default value for this field. This can be a literal value
or a database function, such as :class:`~django.db.models.functions.Now`::
created = models.DateTimeField(db_default=Now())
More complex expressions can be used, as long as they are made from literals
and database functions::
month_due = models.DateField(
db_default=TruncMonth(
Now() + timedelta(days=90),
output_field=models.DateField(),
)
)
Database defaults cannot reference other fields or models. For example, this is
invalid::
end = models.IntegerField(db_default=F("start") + 50)
If both ``db_default`` and :attr:`Field.default` are set, ``default`` will take
precedence when creating instances in Python code. ``db_default`` will still be
set at the database level and will be used when inserting rows outside of the
ORM or when adding a new field in a migration.
``db_index``
------------
.. attribute:: Field.db_index
If ``True``, a database index will be created for this field.
.. admonition:: Use the :attr:`~Options.indexes` option instead.
Where possible, use the :attr:`Meta.indexes <Options.indexes>` option
instead. In nearly all cases, :attr:`~Options.indexes` provides more
functionality than ``db_index``. ``db_index`` may be deprecated in the
future.
``db_tablespace``
-----------------
.. attribute:: Field.db_tablespace
The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
this field's index, if this field is indexed. The default is the project's
:setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the
:attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't
support tablespaces for indexes, this option is ignored.
``default``
-----------
.. attribute:: Field.default
The default value for the field. This can be a value or a callable object. If
callable it will be called every time a new object is created.
The default can't be a mutable object (model instance, ``list``, ``set``, etc.),
as a reference to the same instance of that object would be used as the default
value in all new model instances. Instead, wrap the desired default in a
callable. For example, if you want to specify a default ``dict`` for
:class:`~django.db.models.JSONField`, use a function::
def contact_default():
return {"email": "to1@example.com"}
contact_info = JSONField("ContactInfo", default=contact_default)
``lambda``\s can't be used for field options like ``default`` because they
can't be :ref:`serialized by migrations <migration-serializing>`. See that
documentation for other caveats.
For fields like :class:`ForeignKey` that map to model instances, defaults
should be the value of the field they reference (``pk`` unless
:attr:`~ForeignKey.to_field` is set) instead of model instances.
The default value is used when new model instances are created and a value
isn't provided for the field. When the field is a primary key, the default is
also used when the field is set to ``None``.
The default value can also be set at the database level with
:attr:`Field.db_default`.
``editable``
------------
.. attribute:: Field.editable
If ``False``, the field will not be displayed in the admin or any other
:class:`~django.forms.ModelForm`. They are also skipped during :ref:`model
validation <validating-objects>`. Default is ``True``.
``error_messages``
------------------
.. attribute:: Field.error_messages
The ``error_messages`` argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override.
Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
``unique``, and ``unique_for_date``. Additional error message keys are
specified for each field in the `Field types`_ section below.
These error messages often don't propagate to forms. See
:ref:`considerations-regarding-model-errormessages`.
``help_text``
-------------
.. attribute:: Field.help_text
Extra "help" text to be displayed with the form widget. It's useful for
documentation even if your field isn't used on a form.
Note that this value is *not* HTML-escaped in automatically-generated
forms. This lets you include HTML in :attr:`~Field.help_text` if you so
desire. For example::
help_text = "Please use the following format: <em>YYYY-MM-DD</em>."
Alternatively you can use plain text and
:func:`django.utils.html.escape` to escape any HTML special characters. Ensure
that you escape any help text that may come from untrusted users to avoid a
cross-site scripting attack.
``primary_key``
---------------
.. attribute:: Field.primary_key
If ``True``, this field is the primary key for the model.
If you don't specify ``primary_key=True`` for any field in your model, Django
will automatically add a field to hold the primary key, so you don't need to
set ``primary_key=True`` on any of your fields unless you want to override the
default primary-key behavior. The type of auto-created primary key fields can
be specified per app in :attr:`AppConfig.default_auto_field
<django.apps.AppConfig.default_auto_field>` or globally in the
:setting:`DEFAULT_AUTO_FIELD` setting. For more, see
:ref:`automatic-primary-key-fields`.
``primary_key=True`` implies :attr:`null=False <Field.null>` and
:attr:`unique=True <Field.unique>`. Only one primary key is allowed on an
object.
The primary key field is read-only. If you change the value of the primary
key on an existing object and then save it, a new object will be created
alongside the old one.
The primary key field is set to ``None`` when
:meth:`deleting <django.db.models.Model.delete>` an object.
``unique``
----------
.. attribute:: Field.unique
If ``True``, this field must be unique throughout the table.
This is enforced at the database level and by model validation. If
you try to save a model with a duplicate value in a :attr:`~Field.unique`
field, a :exc:`django.db.IntegrityError` will be raised by the model's
:meth:`~django.db.models.Model.save` method.
This option is valid on all field types except :class:`ManyToManyField` and
:class:`OneToOneField`.
Note that when ``unique`` is ``True``, you don't need to specify
:attr:`~Field.db_index`, because ``unique`` implies the creation of an index.
``unique_for_date``
-------------------
.. attribute:: Field.unique_for_date
Set this to the name of a :class:`DateField` or :class:`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``.
Note that if you set this to point to a :class:`DateTimeField`, only the date
portion of the field will be considered. Besides, when :setting:`USE_TZ` is
``True``, the check will be performed in the :ref:`current time zone
<default-current-time-zone>` at the time the object gets saved.
This is enforced by :meth:`Model.validate_unique()` during model validation
but not at the database level. If any :attr:`~Field.unique_for_date` constraint
involves fields that are not part of a :class:`~django.forms.ModelForm` (for
example, if one of the fields is listed in ``exclude`` or has
:attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will
skip validation for that particular constraint.
``unique_for_month``
--------------------
.. attribute:: Field.unique_for_month
Like :attr:`~Field.unique_for_date`, but requires the field to be unique with
respect to the month.
``unique_for_year``
-------------------
.. attribute:: Field.unique_for_year
Like :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.
``verbose_name``
----------------
.. attribute:: Field.verbose_name
A human-readable name for the field. If the verbose name isn't given, Django
will automatically create it using the field's attribute name, converting
underscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.
``validators``
--------------
.. attribute:: Field.validators
A list of validators to run for this field. See the :doc:`validators
documentation </ref/validators>` for more information.
.. _model-field-types:
Field types
===========
.. currentmodule:: django.db.models
``AutoField``
-------------
.. class:: AutoField(**options)
An :class:`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 :ref:`automatic-primary-key-fields`.
``BigAutoField``
----------------
.. class:: BigAutoField(**options)
A 64-bit integer, much like an :class:`AutoField` except that it is
guaranteed to fit numbers from ``1`` to ``9223372036854775807``.
``BigIntegerField``
-------------------
.. class:: BigIntegerField(**options)
A 64-bit integer, much like an :class:`IntegerField` except that it is
guaranteed to fit numbers from ``-9223372036854775808`` to
``9223372036854775807``. The default form widget for this field is a
:class:`~django.forms.NumberInput`.
``BinaryField``
---------------
.. class:: BinaryField(max_length=None, **options)
A field to store raw binary data. It can be assigned :class:`bytes`,
:class:`bytearray`, or :class:`memoryview`.
By default, ``BinaryField`` sets :attr:`~Field.editable` to ``False``, in which
case it can't be included in a :class:`~django.forms.ModelForm`.
.. attribute:: BinaryField.max_length
Optional. The maximum length (in bytes) of the field. The maximum length is
enforced in Django's validation using
:class:`~django.core.validators.MaxLengthValidator`.
.. admonition:: Abusing ``BinaryField``
Although you might think about storing files in the database, consider that
it is bad design in 99% of the cases. This field is *not* a replacement for
proper :doc:`static files </howto/static-files/index>` handling.
``BooleanField``
----------------
.. class:: BooleanField(**options)
A true/false field.
The default form widget for this field is :class:`~django.forms.CheckboxInput`,
or :class:`~django.forms.NullBooleanSelect` if :attr:`null=True <Field.null>`.
The default value of ``BooleanField`` is ``None`` when :attr:`Field.default`
isn't defined.
``CharField``
-------------
.. class:: CharField(max_length=None, **options)
A string field, for small- to large-sized strings.
For large amounts of text, use :class:`~django.db.models.TextField`.
The default form widget for this field is a :class:`~django.forms.TextInput`.
:class:`CharField` has the following extra arguments:
.. attribute:: CharField.max_length
The maximum length (in characters) of the field. The ``max_length``
is enforced at the database level and in Django's validation using
:class:`~django.core.validators.MaxLengthValidator`. It's required for all
database backends included with Django except PostgreSQL, which supports
unlimited ``VARCHAR`` columns.
.. note::
If you are writing an application that must be portable to multiple
database backends, you should be aware that there are restrictions on
``max_length`` for some backends. Refer to the :doc:`database backend
notes </ref/databases>` for details.
.. attribute:: CharField.db_collation
Optional. The database collation name of the field.
.. note::
Collation names are not standardized. As such, this will not be
portable across multiple database backends.
.. admonition:: Oracle
Oracle supports collations only when the ``MAX_STRING_SIZE`` database
initialization parameter is set to ``EXTENDED``.
``DateField``
-------------
.. class:: DateField(auto_now=False, auto_now_add=False, **options)
A date, represented in Python by a ``datetime.date`` instance. Has a few extra,
optional arguments:
.. attribute:: DateField.auto_now
Automatically set the field to now every time the object is saved. Useful
for "last-modified" timestamps. Note that the current date is *always*
used; it's not just a default value that you can override.
The field is only automatically updated when calling :meth:`Model.save()
<django.db.models.Model.save>`. The field isn't updated when making updates
to other fields in other ways such as :meth:`QuerySet.update()
<django.db.models.query.QuerySet.update>`, though you can specify a custom
value for the field in an update like that.
.. attribute:: DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful
for creation of timestamps. Note that the current date is *always* used;
it's not just a default value that you can override. So even if you
set a value for this field when creating the object, it will be ignored.
If you want to be able to modify this field, set the following instead of
``auto_now_add=True``:
* For :class:`DateField`: ``default=date.today`` - from
:meth:`datetime.date.today`
* For :class:`DateTimeField`: ``default=timezone.now`` - from
:func:`django.utils.timezone.now`
The default form widget for this field is a
:class:`~django.forms.DateInput`. The admin adds a JavaScript calendar,
and a shortcut for "Today". Includes an additional ``invalid_date`` error
message key.
The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.
Any combination of these options will result in an error.
.. note::
As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
``True`` will cause the field to have ``editable=False`` and ``blank=True``
set.
.. note::
The ``auto_now`` and ``auto_now_add`` options will always use the date in
the :ref:`default timezone <default-current-time-zone>` at the moment of
creation or update. If you need something different, you may want to
consider using your own callable default or overriding ``save()`` instead
of using ``auto_now`` or ``auto_now_add``; or using a ``DateTimeField``
instead of a ``DateField`` and deciding how to handle the conversion from
datetime to date at display time.
``DateTimeField``
-----------------
.. class:: DateTimeField(auto_now=False, auto_now_add=False, **options)
A date and time, represented in Python by a ``datetime.datetime`` instance.
Takes the same extra arguments as :class:`DateField`.
The default form widget for this field is a single
:class:`~django.forms.DateTimeInput`. The admin uses two separate
:class:`~django.forms.TextInput` widgets with JavaScript shortcuts.
``DecimalField``
----------------
.. class:: DecimalField(max_digits=None, decimal_places=None, **options)
A fixed-precision decimal number, represented in Python by a
:class:`~decimal.Decimal` instance. It validates the input using
:class:`~django.core.validators.DecimalValidator`.
Has the following **required** arguments:
.. attribute:: DecimalField.max_digits
The maximum number of digits allowed in the number. Note that this number
must be greater than or equal to ``decimal_places``.
.. attribute:: DecimalField.decimal_places
The number of decimal places to store with the number.
For example, to store numbers up to ``999.99`` with a resolution of 2 decimal
places, you'd use::
models.DecimalField(..., max_digits=5, decimal_places=2)
And to store numbers up to approximately one billion with a resolution of 10
decimal places::
models.DecimalField(..., max_digits=19, decimal_places=10)
The default form widget for this field is a :class:`~django.forms.NumberInput`
when :attr:`~django.forms.Field.localize` is ``False`` or
:class:`~django.forms.TextInput` otherwise.
.. note::
For more information about the differences between the
:class:`FloatField` and :class:`DecimalField` classes, please
see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`. You
should also be aware of :ref:`SQLite limitations <sqlite-decimal-handling>`
of decimal fields.
``DurationField``
-----------------
.. class:: DurationField(**options)
A field for storing periods of time - modeled in Python by
:class:`~python:datetime.timedelta`. When used on PostgreSQL, the data type
used is an ``interval`` and on Oracle the data type is ``INTERVAL DAY(9) TO
SECOND(6)``. Otherwise a ``bigint`` of microseconds is used.
.. note::
Arithmetic with ``DurationField`` works in most cases. However on all
databases other than PostgreSQL, comparing the value of a ``DurationField``
to arithmetic on ``DateTimeField`` instances will not work as expected.
``EmailField``
--------------
.. class:: EmailField(max_length=254, **options)
A :class:`CharField` that checks that the value is a valid email address using
:class:`~django.core.validators.EmailValidator`.
``FileField``
-------------
.. class:: FileField(upload_to='', storage=None, max_length=100, **options)
A file-upload field.
.. note::
The ``primary_key`` argument isn't supported and will raise an error if
used.
Has the following optional arguments:
.. attribute:: FileField.upload_to
This attribute provides a way of setting the upload directory and file name,
and can be set in two ways. In both cases, the value is passed to the
:meth:`Storage.save() <django.core.files.storage.Storage.save>` method.
If you specify a string value or a :class:`~pathlib.Path`, it may contain
:func:`~time.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). For example::
class MyModel(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
upload = models.FileField(upload_to="uploads/")
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
upload = models.FileField(upload_to="uploads/%Y/%m/%d/")
If you are using the default
:class:`~django.core.files.storage.FileSystemStorage`, the string value
will be appended to your :setting:`MEDIA_ROOT` path to form the location on
the local filesystem where uploaded files will be stored. If you are using
a different storage, check that storage's documentation to see how it
handles ``upload_to``.
``upload_to`` may also be a callable, such as a function. This will be
called to obtain the upload path, including the filename. This callable must
accept two arguments and return a Unix-style path (with forward slashes)
to be passed along to the storage system. The two arguments are:
====================== ===============================================
Argument Description
====================== ===============================================
``instance`` An instance of the model where the
``FileField`` is defined. More specifically,
this is the particular instance where the
current file is being attached.
In most cases, this object will not have been
saved to the database yet, so if it uses the
default ``AutoField``, *it might not yet have a
value for its primary key field*.
``filename`` The filename that was originally given to the
file. This may or may not be taken into account
when determining the final destination path.
====================== ===============================================
For example::
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return "user_{0}/{1}".format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
.. attribute:: FileField.storage
A storage object, or a callable which returns a storage object. This
handles the storage and retrieval of your files. See :doc:`/topics/files`
for details on how to provide this object.
The default form widget for this field is a
:class:`~django.forms.ClearableFileInput`.
Using a :class:`FileField` or an :class:`ImageField` (see below) in a model
takes a few steps:
#. In your settings file, you'll need to define :setting:`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
:setting:`MEDIA_URL` as the base public URL of that directory. Make sure
that this directory is writable by the web server's user account.
#. Add the :class:`FileField` or :class:`ImageField` to your model, defining
the :attr:`~FileField.upload_to` option to specify a subdirectory of
:setting:`MEDIA_ROOT` to use for uploaded files.
#. All that will be stored in your database is a path to the file
(relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
provided by Django. For example, if your :class:`ImageField` is called
``mug_shot``, you can get the absolute path to your image in a template with
``{{ object.mug_shot.url }}``.
For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
the directory ``/home/media/photos/2007/01/15``.
If you wanted to retrieve the uploaded file's on-disk filename, or the file's
size, you could use the :attr:`~django.core.files.File.name` and
:attr:`~django.core.files.File.size` attributes respectively; for more
information on the available attributes and methods, see the
:class:`~django.core.files.File` class reference and the :doc:`/topics/files`