Encode django QuerySets to lists and not dicts in JSONEncoder

This commit is contained in:
Mathieu Pillard 2014-01-17 13:05:10 +01:00
parent 71c03b9db9
commit f034cb595a
2 changed files with 22 additions and 0 deletions

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from decimal import Decimal from decimal import Decimal
from django.core.cache import cache from django.core.cache import cache
from django.db import models
from django.test import TestCase from django.test import TestCase
from django.utils import unittest from django.utils import unittest
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -34,6 +35,10 @@ expected_results = [
] ]
class DummyTestModel(models.Model):
name = models.CharField(max_length=42, default='')
class BasicRendererTests(TestCase): class BasicRendererTests(TestCase):
def test_expected_results(self): def test_expected_results(self):
for value, renderer_cls, expected in expected_results: for value, renderer_cls, expected in expected_results:
@ -276,6 +281,20 @@ class JSONRendererTests(TestCase):
ret = JSONRenderer().render(_('test')) ret = JSONRenderer().render(_('test'))
self.assertEqual(ret, b'"test"') self.assertEqual(ret, b'"test"')
def test_render_queryset_values(self):
o = DummyTestModel.objects.create(name='dummy')
qs = DummyTestModel.objects.values('id', 'name')
ret = JSONRenderer().render(qs)
data = json.loads(ret.decode('utf-8'))
self.assertEquals(data, [{'id': o.id, 'name': o.name}])
def test_render_queryset_values_list(self):
o = DummyTestModel.objects.create(name='dummy')
qs = DummyTestModel.objects.values_list('id', 'name')
ret = JSONRenderer().render(qs)
data = json.loads(ret.decode('utf-8'))
self.assertEquals(data, [[o.id, o.name]])
def test_render_dict_abc_obj(self): def test_render_dict_abc_obj(self):
class Dict(MutableMapping): class Dict(MutableMapping):
def __init__(self): def __init__(self):

View File

@ -2,6 +2,7 @@
Helper classes for parsers. Helper classes for parsers.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.db.models.query import QuerySet
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.functional import Promise from django.utils.functional import Promise
from rest_framework.compat import timezone, force_text from rest_framework.compat import timezone, force_text
@ -42,6 +43,8 @@ class JSONEncoder(json.JSONEncoder):
return str(o.total_seconds()) return str(o.total_seconds())
elif isinstance(o, decimal.Decimal): elif isinstance(o, decimal.Decimal):
return str(o) return str(o)
elif isinstance(o, QuerySet):
return list(o)
elif hasattr(o, 'tolist'): elif hasattr(o, 'tolist'):
return o.tolist() return o.tolist()
elif hasattr(o, '__getitem__'): elif hasattr(o, '__getitem__'):