1
0
mirror of https://github.com/django/django.git synced 2025-10-24 14:16:09 +00:00

Refs #29738 -- Allowed registering serializers with MigrationWriter.

This commit is contained in:
can
2019-01-10 21:05:19 +03:00
committed by Tim Graham
parent 3c01fe30f3
commit 7d3b3897c1
5 changed files with 93 additions and 37 deletions

View File

@@ -211,6 +211,9 @@ Migrations
* ``NoneType`` can now be serialized in migrations.
* You can now :ref:`register custom serializers <custom-migration-serializers>`
for migrations.
Models
~~~~~~

View File

@@ -697,6 +697,35 @@ Django cannot serialize:
- Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)
- Lambdas
.. _custom-migration-serializers:
Custom serializers
------------------
.. versionadded:: 2.2
You can serialize other types by writing a custom serializer. For example, if
Django didn't serialize :class:`~decimal.Decimal` by default, you could do
this::
from decimal import Decimal
from django.db.migrations.serializer import BaseSerializer
from django.db.migrations.writer import MigrationWriter
class DecimalSerializer(BaseSerializer):
def serialize(self):
return repr(self.value), {'from decimal import Decimal'}
MigrationWriter.register_serializer(Decimal, DecimalSerializer)
The first argument of ``MigrationWriter.register_serializer()`` is a type or
iterable of types that should use the serializer.
The ``serialize()`` method of your serializer must return a string of how the
value should appear in migrations and a set of any imports that are needed in
the migration.
.. _custom-deconstruct-method:
Adding a ``deconstruct()`` method