summaryrefslogtreecommitdiff
path: root/docs/ref
diff options
context:
space:
mode:
authorNatalia <124304+nessita@users.noreply.github.com>2023-08-31 09:09:30 -0300
committerNatalia <124304+nessita@users.noreply.github.com>2023-09-14 10:15:33 -0300
commit691f70c47755c7f55fa75ce607d028f81468b745 (patch)
tree4d791a30d85e51c0362dfa6fb85a518758affeb5 /docs/ref
parent5bfb3cbf49e2b9701e7c42989e14a72374adb6bd (diff)
Fixed #24561 -- Added support for callables on model fields' choices.
Diffstat (limited to 'docs/ref')
-rw-r--r--docs/ref/models/fields.txt25
1 files changed, 24 insertions, 1 deletions
diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt
index a41eb7b1d2..7ad9f77741 100644
--- a/docs/ref/models/fields.txt
+++ b/docs/ref/models/fields.txt
@@ -115,9 +115,32 @@ human-readable name. For example::
("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 was added.
+ 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::