diff --git a/rest_framework/tests/test_renderers.py b/rest_framework/tests/test_renderers.py index 2ae8ae18c..fb33df2cf 100644 --- a/rest_framework/tests/test_renderers.py +++ b/rest_framework/tests/test_renderers.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from decimal import Decimal from django.core.cache import cache +from django.db import models from django.test import TestCase from django.utils import unittest 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): def test_expected_results(self): for value, renderer_cls, expected in expected_results: @@ -276,6 +281,20 @@ class JSONRendererTests(TestCase): ret = JSONRenderer().render(_('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): class Dict(MutableMapping): def __init__(self): diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 3ac920c6f..e5fa41947 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -2,6 +2,7 @@ Helper classes for parsers. """ from __future__ import unicode_literals +from django.db.models.query import QuerySet from django.utils.datastructures import SortedDict from django.utils.functional import Promise from rest_framework.compat import timezone, force_text @@ -42,6 +43,8 @@ class JSONEncoder(json.JSONEncoder): return str(o.total_seconds()) elif isinstance(o, decimal.Decimal): return str(o) + elif isinstance(o, QuerySet): + return list(o) elif hasattr(o, 'tolist'): return o.tolist() elif hasattr(o, '__getitem__'):