Skip to content

Instantly share code, notes, and snippets.

@antdking
Created January 16, 2018 09:11
Show Gist options
  • Save antdking/2476434c513170d2f267cb588a8d645b to your computer and use it in GitHub Desktop.
Save antdking/2476434c513170d2f267cb588a8d645b to your computer and use it in GitHub Desktop.
from django.core.serializers.json import Serializer as JsonSerializer
# because of the way serializers are registered, we need to import the Deserializer
from django.core.serializers.json import Deserializer # noqa
# There's a bug in Django currently, and it doesn't look like it'll be fixed till Django 2.1.
# https://code.djangoproject.com/ticket/24607
# Changes are based on https://github.com/django/django/pull/8370
# To use this, configure SERIALIZATION_MODULES
# SERIALIZATION_MODULES = {
# 'patched_json': 'path.to.patched_json_serializer',
# }
# then run dumpdata like so:
# `python manage.py dumpdata --format=patched_json`
class Serializer(JsonSerializer):
def get_dump_object(self, obj):
self._patch_parent_link_natural_key(obj)
return super().get_dump_object(obj)
def _patch_parent_link_natural_key(self, obj):
if not self.use_natural_foreign_keys:
return
# note: undocumented API
# Avoid running that aren't inherited
if not obj._meta.parents:
return
# Use the concrete parent class' _meta instead of the object's _meta
# This is to avoid local_fields problems for proxy models. Refs #17717.
concrete_model = obj._meta.concrete_model
pk = concrete_model._meta.pk
pk_is_parent = bool(pk and pk.remote_field and pk.remote_field.parent_link)
if pk_is_parent:
self.handle_fk_field(obj, pk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment