diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py index 66dbbff3350..5fbb3163f78 100644 --- a/django/core/serializers/python.py +++ b/django/core/serializers/python.py @@ -37,7 +37,12 @@ class Serializer(base.Serializer): def handle_fk_field(self, obj, field): related = getattr(obj, field.name) if related is not None: - related = getattr(related, field.rel.field_name) + if field.rel.field_name == related._meta.pk.name: + # Related to remote object via primary key + related = related._get_pk_val() + else: + # Related to remote object via other field + related = getattr(related, field.rel.field_name) self._current[field.name] = related def handle_m2m_field(self, obj, field): diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index 633001f5f06..3e4a6f3e795 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -82,7 +82,13 @@ class Serializer(base.Serializer): self._start_relational_field(field) related = getattr(obj, field.name) if related is not None: - self.xml.characters(str(getattr(related, field.rel.field_name))) + if field.rel.field_name == related._meta.pk.name: + # Related to remote object via primary key + related = related._get_pk_val() + else: + # Related to remote object via other field + related = getattr(related, field.rel.field_name) + self.xml.characters(str(related)) else: self.xml.addQuickElement("None") self.xml.endElement("field") diff --git a/tests/regressiontests/serializers_regress/models.py b/tests/regressiontests/serializers_regress/models.py index 999b79ccafc..3b9c228d4c6 100644 --- a/tests/regressiontests/serializers_regress/models.py +++ b/tests/regressiontests/serializers_regress/models.py @@ -129,6 +129,9 @@ class M2MSelfData(models.Model): class FKDataToField(models.Model): data = models.ForeignKey(UniqueAnchor, null=True, to_field='data') +class FKDataToO2O(models.Model): + data = models.ForeignKey(O2OData, null=True) + # The following test classes are for validating the # deserialization of objects that use a user-defined # field as the primary key. diff --git a/tests/regressiontests/serializers_regress/tests.py b/tests/regressiontests/serializers_regress/tests.py index 5df4c6818a1..dd724093aa0 100644 --- a/tests/regressiontests/serializers_regress/tests.py +++ b/tests/regressiontests/serializers_regress/tests.py @@ -197,6 +197,8 @@ The end."""), (fk_obj, 451, FKDataToField, "UAnchor 2"), (fk_obj, 452, FKDataToField, None), + (fk_obj, 460, FKDataToO2O, 300), + (data_obj, 500, Anchor, "Anchor 3"), (data_obj, 501, Anchor, "Anchor 4"), (data_obj, 502, UniqueAnchor, "UAnchor 2"),