mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-22 09:36:49 +03:00
Encode django QuerySets to lists and not dicts in JSONEncoder
This commit is contained in:
parent
71c03b9db9
commit
f034cb595a
|
@ -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):
|
||||
|
|
|
@ -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__'):
|
||||
|
|
Loading…
Reference in New Issue
Block a user