Fix None UUID ForeignKey serialization

This commit is contained in:
Carlton Gibson 2016-02-16 09:29:48 +01:00
parent 79dad012b0
commit 20d1fdba69
4 changed files with 38 additions and 1 deletions

View File

@ -45,6 +45,7 @@ You can determine your currently installed version using `pip freeze`:
**Unreleased**
* Dropped support for EOL Django 1.7 ([#3933][gh3933])
* Fixed null foreign keys targeting UUIDField primary keys. ([#3936][gh3936])
### 3.3.2

View File

@ -778,6 +778,8 @@ class UUIDField(Field):
return data
def to_representation(self, value):
if value is None:
return None
if self.uuid_format == 'hex_verbose':
return str(value)
else:

View File

@ -1,5 +1,7 @@
from __future__ import unicode_literals
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
@ -46,6 +48,11 @@ class ForeignKeyTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)
class UUIDForeignKeyTarget(RESTFrameworkModel):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=100)
class ForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, related_name='sources',
@ -62,6 +69,14 @@ class NullableForeignKeySource(RESTFrameworkModel):
on_delete=models.CASCADE)
class NullableUUIDForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources',
verbose_name='Optional target object',
on_delete=models.CASCADE)
# OneToOne
class OneToOneTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)

View File

@ -6,7 +6,8 @@ from django.utils import six
from rest_framework import serializers
from tests.models import (
ForeignKeySource, ForeignKeyTarget, ManyToManySource, ManyToManyTarget,
NullableForeignKeySource, NullableOneToOneSource, OneToOneTarget
NullableForeignKeySource, NullableOneToOneSource,
NullableUUIDForeignKeySource, OneToOneTarget, UUIDForeignKeyTarget
)
@ -43,6 +44,18 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
fields = ('id', 'name', 'target')
# Nullable UUIDForeignKey
class NullableUUIDForeignKeySourceSerializer(serializers.ModelSerializer):
target = serializers.PrimaryKeyRelatedField(
pk_field=serializers.UUIDField(),
queryset=UUIDForeignKeyTarget.objects.all(),
allow_empty=True)
class Meta:
model = NullableUUIDForeignKeySource
fields = ('id', 'name', 'target')
# Nullable OneToOne
class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
class Meta:
@ -432,6 +445,12 @@ class PKNullableForeignKeyTests(TestCase):
]
self.assertEqual(serializer.data, expected)
def test_null_uuid_foreign_key_serializes_as_none(self):
source = NullableUUIDForeignKeySource(name='Source')
serializer = NullableUUIDForeignKeySourceSerializer(source)
data = serializer.data
self.assertEqual(data["target"], None)
class PKNullableOneToOneTests(TestCase):
def setUp(self):