mirror of
https://github.com/django/django.git
synced 2025-07-24 05:36:15 +00:00
Fixed #25995 -- Added an encoder option to JSONField
Thanks Berker Peksag and Tim Graham for the reviews.
This commit is contained in:
parent
989f6108d3
commit
13c3e5d5a0
7 changed files with 98 additions and 10 deletions
|
@ -458,17 +458,32 @@ using in conjunction with lookups on
|
|||
``JSONField``
|
||||
=============
|
||||
|
||||
.. class:: JSONField(**options)
|
||||
.. class:: JSONField(encoder=None, **options)
|
||||
|
||||
A field for storing JSON encoded data. In Python the data is represented in
|
||||
its Python native format: dictionaries, lists, strings, numbers, booleans
|
||||
and ``None``.
|
||||
|
||||
If you want to store other data types, you'll need to serialize them first.
|
||||
For example, you might cast a ``datetime`` to a string. You might also want
|
||||
to convert the string back to a ``datetime`` when you retrieve the data
|
||||
from the database. There are some third-party ``JSONField`` implementations
|
||||
which do this sort of thing automatically.
|
||||
.. attribute:: encoder
|
||||
|
||||
.. versionadded:: 1.11
|
||||
|
||||
An optional JSON-encoding class to serialize data types not supported
|
||||
by the standard JSON serializer (``datetime``, ``uuid``, etc.). For
|
||||
example, you can use the
|
||||
:class:`~django.core.serializers.json.DjangoJSONEncoder` class or any
|
||||
other :py:class:`json.JSONEncoder` subclass.
|
||||
|
||||
When the value is retrieved from the database, it will be in the format
|
||||
chosen by the custom encoder (most often a string), so you'll need to
|
||||
take extra steps to convert the value back to the initial data type
|
||||
(:meth:`Model.from_db() <django.db.models.Model.from_db>` and
|
||||
:meth:`Field.from_db_value() <django.db.models.Field.from_db_value>`
|
||||
are two possible hooks for that purpose). Your deserialization may need
|
||||
to account for the fact that you can't be certain of the input type.
|
||||
For example, you run the risk of returning a ``datetime`` that was
|
||||
actually a string that just happened to be in the same format chosen
|
||||
for ``datetime``\s.
|
||||
|
||||
If you give the field a :attr:`~django.db.models.Field.default`, ensure
|
||||
it's a callable such as ``dict`` (for an empty default) or a callable that
|
||||
|
|
|
@ -129,6 +129,10 @@ Minor features
|
|||
* The new :class:`~django.contrib.postgres.indexes.GinIndex` class allows
|
||||
creating gin indexes in the database.
|
||||
|
||||
* :class:`~django.contrib.postgres.fields.JSONField` accepts a new ``encoder``
|
||||
parameter to specify a custom class to encode data types not supported by the
|
||||
standard encoder.
|
||||
|
||||
:mod:`django.contrib.redirects`
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue