How to use the restless.models.serialize function in restless

To help you get started, we’ve selected a few restless examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_queryset(self):
        """Test queryset serialization"""

        Author.objects.all().delete()
        a1 = Author.objects.create(name="foo")
        a2 = Author.objects.create(name="bar")
        qs = Author.objects.all()
        _ = list(qs)  # force sql query execution

        # Check that the same (cached) queryset is used, instead of a clone
        with self.assertNumQueries(0):
            s = serialize(qs)

        self.assertEqual(s,
            [
                {'name': a1.name, 'id': a1.id},
                {'name': a2.name, 'id': a2.id},
            ]
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_shallow_foreign_key_serialization(self):
        """Test that foreign key fields are serialized as integer IDs."""

        s = serialize(self.books[0])
        self.assertEqual(s['author'], self.author.id)
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_doesnt_mutate_fields(self):
        runs = [0]

        def accessor(obj):
            runs[0] += 1
            return 'foo'

        # If fields are appended on, 'desc' will be twice in the list
        # for the second run, so in total the accessor function will be
        # run 3 instead of 2 times
        serialize([self.author, self.author], fields=['id'],
            include=[('desc', accessor)])

        self.assertEqual(runs[0], 2)
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_related_deep(self):
        """Test serialization of twice-removed related model"""

        s = serialize(self.author, include=[
            ('books', dict(
                include=[('publisher', dict())]
            ))
        ])

        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertEqual(b['publisher']['name'], 'Publisher')
github dobarkod / django-restless / testproject / testapp / views.py View on Github external
def get(self, request):
        return serialize(request.user)
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_related_flatten(self):
        """Test injection of related models' fields into the serialized one"""

        b = self.books[0]
        s = serialize(b, fields=[
            ('author', dict())
        ], fixup=flatten('author'))

        self.assertEqual(s['name'], b.author.name)
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_takes_fields_tuple(self):
        s = serialize(self.author, fields=('id',), include=('name',))
        self.assertEqual(s, {
            'id': self.author.id,
            'name': self.author.name
        })
github dobarkod / django-restless / testproject / testapp / tests.py View on Github external
def test_serialize_related_partial_deprecated(self):
        """Test serialization of some fields of related model"""

        with warnings.catch_warnings(record=True):
            s = serialize(self.author, related={
                'books': ('title', None, False)
            })
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue('isbn' not in b)
github opencivicdata / imago / imago / helpers.py View on Github external
except EmptyPage:
            raise HttpError(404, 'No such page (heh, literally - its out of bounds)')

        self.start_debug()

        count = data_page.paginator.count

        response = {
            "meta": {
                "count": len(data_page.object_list),
                "page": page,
                "per_page": per_page,
                "max_page": math.ceil(count / per_page),
                "total_count": count,
            }, "results": [
                serialize(x, **config) for x in data_page.object_list
            ]
        }

        if settings.DEBUG:
            response['debug'] = self.get_debug()
            response['debug'].update({
                "prefetch_fields": list(related),
                "page": page,
                "sort": sort_by,
                "field": fields,
            })

        response = Http200(response)

        response['Access-Control-Allow-Origin'] = "*"
        return response