Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use field.value_to_string(model) for any non protected type #40

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ dist/
.tox/
MANIFEST
/django_modelcluster.egg-info
.eggs
18 changes: 8 additions & 10 deletions modelcluster/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ def get_related_model(rel):


def get_field_value(field, model):
if field.rel is None:
value = field._get_val_from_obj(model)

value = field._get_val_from_obj(model)

if not is_protected_type(value):
value = field.value_to_string(model)

elif field.rel is None:
# Make datetimes timezone aware
# https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1394-L1403
if isinstance(value, datetime.datetime) and settings.USE_TZ:
Expand All @@ -35,13 +38,8 @@ def get_field_value(field, model):
value = timezone.make_aware(value, default_timezone).astimezone(timezone.utc)
# convert to UTC
value = timezone.localtime(value, timezone.utc)

if is_protected_type(value):
return value
else:
return field.value_to_string(model)
else:
return getattr(model, field.get_attname())

return value

def get_serializable_data_for_fields(model):
pk_field = model._meta.pk
Expand Down
27 changes: 27 additions & 0 deletions tests/migrations/0002_barmodel_foomodel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import tests.models


class Migration(migrations.Migration):

dependencies = [
('tests', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='FooModel',
fields=[
('id', tests.models.FooField(serialize=False, primary_key=True)),
],
),
migrations.CreateModel(
name='BarModel',
fields=[
('id', models.OneToOneField(primary_key=True, serialize=False, to='tests.FooModel')),
],
),
]
53 changes: 53 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import unicode_literals

import base64

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.six import text_type

from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
Expand Down Expand Up @@ -107,3 +110,53 @@ class Log(ClusterableModel):

def __str__(self):
return "[%s] %s" % (self.time.isoformat(), self.data)


@python_2_unicode_compatible
class FooValue(object):
value = None

def __init__(self, value):
super(FooValue, self).__init__()
self.value = int(value)

def __str__(self):
return text_type(base64.b64encode(text_type(self.value).encode("utf-8")).strip())

def __int__(self):
return self.value


class FooField(models.IntegerField):
def get_prep_value(self, value):
if isinstance(value, FooValue):
value = int(value)
return value

def get_db_prep_value(self, *args, **kwargs):
value = super(FooField, self).get_db_prep_value(*args, **kwargs)
if isinstance(value, FooValue):
value = int(value)
return value

def to_python(self, value):
if value is not None and not isinstance(value, FooValue):
value = FooValue(value)
return value

def from_db_value(self, value, expression, connection, context):
if not isinstance(value, FooValue):
value = FooValue(value)
return value


@python_2_unicode_compatible
class FooModel(models.Model):
id = FooField(primary_key=True)

def __str__(self):
return text_type("{} instance, id {}".format(self.__class__, self.id))

class BarModel(models.Model):
id = models.OneToOneField(FooModel, primary_key=True)

29 changes: 27 additions & 2 deletions tests/tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
import json
import datetime

from django import VERSION as DJANGO_VERSION
from django.test import TestCase
from django.utils import timezone
from django.utils.encoding import is_protected_type
from django.utils.six import text_type, string_types

from tests.models import Band, BandMember, Album, Restaurant, Dish, MenuItem, Chef, Wine, Review, Log
from modelcluster.models import get_serializable_data_for_fields

from tests.models import Band, BandMember, Album, Restaurant, Dish, MenuItem, Chef, Wine, Review, Log, FooModel, FooValue, BarModel

from unittest import skipIf


class SerializeTest(TestCase):
Expand All @@ -18,7 +25,25 @@ def test_serialize(self):

expected = {'pk': None, 'albums': [], 'name': 'The Beatles', 'members': [{'pk': None, 'name': 'John Lennon', 'band': None}, {'pk': None, 'name': 'Paul McCartney', 'band': None}]}
self.assertEqual(expected, beatles.serializable_data())


@skipIf(DJANGO_VERSION < (1, 8), "test model fields use `from_db_value()` introduced in DJ18")
def test_serialize_related_to_custom_type(self):
FooModel.objects.create(id=1)
foo_obj = FooModel.objects.get()
self.assertFalse(is_protected_type(foo_obj.id))
foo_data = get_serializable_data_for_fields(foo_obj)
data_pk = foo_data["pk"]
self.assertNotIsInstance(data_pk, FooValue)
self.assertEqual(data_pk, text_type(foo_obj.id))

BarModel.objects.create(id=foo_obj)
bar_obj = BarModel.objects.get()
self.assertFalse(is_protected_type(bar_obj.id))
self.assertEqual(text_type(bar_obj.id), text_type(foo_obj))
self.assertIsInstance(bar_obj.id, FooModel)
bar_data = get_serializable_data_for_fields(bar_obj)
self.assertIsInstance(bar_data["pk"], string_types)

def test_serialize_json_with_dates(self):
beatles = Band(name='The Beatles', members=[
BandMember(name='John Lennon'),
Expand Down