django.core.serializers.serialize

Here are the examples of the python api django.core.serializers.serialize taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

159 Examples 7

Example 1

Project: django-compositepks Source File: tests.py
def streamTest(format, self):
    # Clear the database first
    management.call_command('flush', verbosity=0, interactive=False)

    obj = ComplexModel(field1='first',field2='second',field3='third')
    obj.save_base(raw=True)

    # Serialize the test database to a stream
    stream = StringIO()
    serializers.serialize(format, [obj], indent=2, stream=stream)

    # Serialize normally for a comparison
    string_data = serializers.serialize(format, [obj], indent=2)

    # Check that the two are the same
    self.assertEqual(string_data, stream.getvalue())
    stream.close()

Example 2

Project: django-newsletter Source File: admin.py
    def subscribers_json(self, request, object_id):
        message = self._getobj(request, object_id)

        json = serializers.serialize(
            "json", message.newsletter.get_subscriptions(), fields=()
        )
        return HttpResponse(json, content_type='application/json')

Example 3

Project: agagd Source File: json_response.py
Function: init
    def __init__(self, object):
        if isinstance(object, QuerySet):
            content = serialize('json', object)
        else:
            content = simplejson.dumps(
                object, indent=2, cls=json.DjangoJSONEncoder,
                ensure_ascii=False)
        super(JsonResponse, self).__init__(
            content, content_type='application/json')

Example 4

Project: django-riv Source File: serializers.py
Function: testserializechoiceexcludeforeignkeywithoutinline
    def testSerializeChoiceExcludeForeignKeyWithoutInline(self):
        """
        This test should simply ignore the exclude setting.
        """
        self.assertEqual(
            serializers.serialize('rest', self.choice1, exclude=['poll__question',]),
            {'votes': self.choice1.votes, 'poll': self.choice1.poll.id, 'id': self.choice1.id, 'choice': self.choice1.choice}
        )

Example 5

Project: django-braces Source File: _ajax.py
    def render_json_object_response(self, objects, **kwargs):
        """
        Serializes objects using Django's builtin JSON serializer. Additional
        kwargs can be used the same way for django.core.serializers.serialize.
        """
        json_data = serializers.serialize("json", objects, **kwargs)
        return HttpResponse(json_data, content_type=self.get_content_type())

Example 6

Project: extdirect.django Source File: crud.py
Function: load
    def load(self, request):
        #Almost the same as 'read' action but here we call
        #the serializer directly with a fixed metadata (different
        #from the self.store). Besides, we assume that the load
        #action should return a single record, so all the query
        #options are not needed.
        meta = self.direct_load_metadata
        extdirect_data = self.extract_load_data(request)
        ok, msg = self.pre_load(extdirect_data)         
        if ok:                  
            queryset = self.model.objects.filter(**extdirect_data)
            res = serialize('extdirect', queryset, meta=meta, single_cast=True)
            return res
        else:
            return self.failure(msg)                        

Example 7

Project: django-oscar Source File: views.py
Function: store_object
    def _store_object(self, form):
        session_data = self.request.session.setdefault(self.wizard_name, {})

        # We don't store the object instance as that is not JSON serialisable.
        # Instead, we save an alternative form
        instance = form.save(commit=False)
        json_qs = serializers.serialize('json', [instance])

        session_data[self._key(is_object=True)] = json_qs
        self.request.session.save()

Example 8

Project: python-semanticversion Source File: test_django.py
    def test_serialization_partial(self):
        o1 = models.PartialVersionModel(
            partial=Version('0.1.1', partial=True),
            optional=Version('0.2.4-rc42', partial=True),
            optional_spec=None,
        )
        o2 = models.PartialVersionModel(
            partial=Version('0.4.3-rc3+build3', partial=True),
            optional='',
            optional_spec=Spec('==0.1.1,!=0.1.1-alpha'),
        )

        data = serializers.serialize('json', [o1, o2])

        obj1, obj2 = serializers.deserialize('json', data)
        self.assertEqual(o1.partial, obj1.object.partial)
        self.assertEqual(o1.optional, obj1.object.optional)
        self.assertEqual(o2.partial, obj2.object.partial)
        self.assertEqual(o2.optional, obj2.object.optional)

Example 9

Project: edx-platform Source File: json_request.py
Function: init
    def __init__(self, resp_obj=None, status=None, encoder=EDXJSONEncoder,
                 *args, **kwargs):
        if resp_obj in (None, ""):
            content = ""
            status = status or 204
        elif isinstance(resp_obj, QuerySet):
            content = serialize('json', resp_obj)
        else:
            content = json.dumps(resp_obj, cls=encoder, indent=2, ensure_ascii=True)
        kwargs.setdefault("content_type", "application/json")
        if status:
            kwargs["status"] = status
        super(JsonResponse, self).__init__(content, *args, **kwargs)

Example 10

Project: sci-wms Source File: views.py
Function: post
    @method_decorator(csrf_protect)
    def post(self, request):
        try:
            uri = request.POST['uri']
            name = request.POST['name']
            assert uri and name
        except (AssertionError, KeyError):
            return HttpResponse('URI and Name are required. Please try again.', status=500, reason="Could not process inputs", content_type="text/plain")

        klass = Dataset.identify(uri)
        if klass is not None:
            try:
                ds = klass.objects.create(uri=uri, name=name)
            except IntegrityError:
                return HttpResponse('Name is already taken, please choose another', status=500, reason="Could not process inputs", content_type="application/json")

            return HttpResponse(serializers.serialize('json', [ds]), status=201, content_type="application/json")
        else:
            return HttpResponse('Could not process the URI with any of the available Dataset types. Please check the URI and try again', status=500, reason="Could not process inputs", content_type="application/json")

Example 11

Project: django-typed-models Source File: tests.py
    def _check_serialization(self, serialization_format):
        """Helper function used to check serialization and deserialization for concrete format."""
        animals = Animal.objects.order_by('pk')
        serialized_animals = serializers.serialize(serialization_format, animals)
        deserialized_animals = [wrapper.object for wrapper in serializers.deserialize(serialization_format, serialized_animals)]
        self.assertEqual(set(deserialized_animals), set(animals))

Example 12

Project: django-mysql Source File: test_bit1_field.py
Function: test_dumping
    def test_dumping(self):
        instance = Bit1Model(flag_a=True, flag_b=False)
        data = json.loads(serializers.serialize('json', [instance]))[0]
        fields = data['fields']
        assert fields['flag_a']
        assert not fields['flag_b']

Example 13

Project: django-arrayfields Source File: tests.py
Function: test_serialization
    def test_serialization(self):
        item = Item.objects.create(text=[['abc'],['xyz']])
        s = serializers.serialize('json', list(Item.objects.all()))
        item.delete()
        s = s.replace('abc', 'def')
        for obj in serializers.deserialize('json', s):
            obj.save()
        self.assertEqual(Item.objects.get().text, [['def'],['xyz']])

Example 14

Project: django-riv Source File: serializers.py
Function: testserializechoiceexcludeforeignkeywithoutinline
    def testSerializeChoiceExcludeForeignKeyWithoutInline(self):
        """
        This test should simply ignore the exclude setting.
        """
        xmlstring = '<?xml version="1.0" encoding="utf-8"?><objects><choice><votes>%d</votes><poll>%d</poll><id>%d</id><choice>%s</choice></choice></objects>' % (self.choice1.votes, self.choice1.poll.id, self.choice1.id, self.choice1.choice)
        result_xml = ET.fromstring(xmlstring)
        serialized_xml = ET.fromstring(serializers.serialize('restxml', self.choice1, exclude=['poll__question',]))
        self.assertTrue(xml_compare(result_xml, serialized_xml))

Example 15

Project: django_xworkflows Source File: tests.py
    def test_dumping(self):
        o = models.MyWorkflowEnabled()
        o.state = o.state.workflow.states.bar
        o.save()

        self.assertTrue(o.state.is_bar)

        data = serializers.serialize('json',
                models.MyWorkflowEnabled.objects.filter(pk=o.id))

        models.MyWorkflowEnabled.objects.all().delete()

        for obj in serializers.deserialize('json', data):
            obj.object.save()

        obj = models.MyWorkflowEnabled.objects.all()[0]
        self.assertTrue(obj.state.is_bar)

Example 16

Project: djangotoolbox Source File: tests.py
    def test_json_listfield(self):
        for i in range(1, 5):
            ListModel(integer=i, floating_point=0,
                      names=SerializationTest.names[:i]).save()
        objects = ListModel.objects.all()
        serialized = serializers.serialize('json', objects)
        deserialized = serializers.deserialize('json', serialized)
        for m in deserialized:
            integer = m.object.integer
            names = m.object.names
            self.assertEqual(names, SerializationTest.names[:integer])

Example 17

Project: jaikuenginepatch Source File: tests.py
    def test_serializer(self, format='json'):
        from django.core import serializers
        created = datetime.now()
        x = SerializeModel(key_name='blue_key', name='blue', count=4)
        x.put()
        SerializeModel(name='green', count=1, created=created).put()
        data = serializers.serialize(format, SerializeModel.all())
        db.delete(SerializeModel.all().fetch(100))
        for obj in serializers.deserialize(format, data):
            obj.save()
        self.validate_state(
            ('key.name', 'name',  'count', 'created'),
            (None,       'green', 1, created),
            ('blue_key', 'blue',  4, None),
        )

Example 18

Project: django-pgjson Source File: tests.py
Function: test_to_python_serializes_xml_correctly
    def test_to_python_serializes_xml_correctly(self):
        obj = self.model_class.objects.create(data={"a": 0.2})

        serialized_obj = serialize('xml', self.model_class.objects.filter(pk=obj.pk))

        obj.delete()
        deserialized_obj = list(deserialize('xml', serialized_obj))[0]

        obj = deserialized_obj.object
        obj.save()
        obj = obj.__class__.objects.get(pk=obj.pk)

        self.assertEqual(obj.data, {"a": 0.2})

Example 19

Project: probr-core Source File: models.py
def publishPostSaveMessage(sender, instance, created, **kwargs):
    payload = serializers.serialize('json', [instance, ])
    struct = json.loads(payload)
    struct[0]['fields']['object_type'] = instance._meta.verbose_name + ':update'
    struct[0]['fields']['uuid'] = instance.uuid # also send uuid
    payload = json.dumps(struct[0]['fields'])

    # also publish to foreign key fields, to enable grouping/filtering on client-side
    # for field in instance._meta.fields:
    #    if field.get_internal_type() == "ForeignKey":
    #        group = field.name + '-' + getattr(instance, field.name).uuid
    #        publishMessage(instance._meta.verbose_name_plural, message=payload, groups=[group])

    publishMessage("socket", message=payload)

Example 20

Project: django-any-urlfield Source File: tests.py
    def test_dumpdata(self):
        """
        See if the dumpdata routines handle the value properly.
        """
        page2 = RegPageModel.objects.create(slug='foo2')
        UrlModel.objects.create(
            url=AnyUrlValue.from_model(page2)
        )

        json_data = serializers.serialize("json", UrlModel.objects.all())
        data = json.loads(json_data)
        self.assertEqual(data, [{"fields": {"url": "any_urlfield.regpagemodel://1"}, "model": "any_urlfield.urlmodel", "pk": 1}])

Example 21

Project: django-happenings Source File: mixins.py
    @staticmethod
    def get_day_context_dict(context):
        events = loads(serializers.serialize("json", context['events']))
        return dict(
            events=events,
            year=context['year'],
            month=context['month_num'],
            month_name=context['month'],
            day=context['day'],
            nxt=context['next'],
            prev=context['prev'],
        )

Example 22

Project: django-api Source File: json_helpers.py
    def default(self, obj):
        """
        Convert QuerySet objects to their list counter-parts
        """
        if isinstance(obj, models.Model):
            return self.encode(model_to_dict(obj))
        elif isinstance(obj, models.query.QuerySet):
            return serializers.serialize('json', obj)
        else:
            return super(JsonResponseEncoder, self).default(obj)

Example 23

Project: edison Source File: emitters.py
Function: render
    def render(self, request, format='xml'):
        if isinstance(self.data, HttpResponse):
            return self.data
        elif isinstance(self.data, (int, str)):
            response = self.data
        else:
            response = serializers.serialize(format, self.data, indent=True)

        return response

Example 24

Project: django-jsonfield Source File: tests.py
    def test_django_serializers(self):
        """Test serializing/deserializing jsonfield data"""
        for json_obj in [{}, [], 0, '', False, {'key': 'value', 'num': 42,
                                                'ary': list(range(5)),
                                                'dict': {'k': 'v'}}]:
            obj = self.json_model.objects.create(json=json_obj)
            new_obj = self.json_model.objects.get(id=obj.id)
            self.assert_(new_obj)

        queryset = self.json_model.objects.all()
        ser = serialize('json', queryset)
        for dobj in deserialize('json', ser):
            obj = dobj.object
            pulled = self.json_model.objects.get(id=obj.pk)
            self.assertEqual(obj.json, pulled.json)

Example 25

Project: coursys Source File: devtest_importer.py
Function: serialize_result
def serialize_result(data_func, filename):
    print "creating %s.json" % (filename)
    start = time.time()
    objs = data_func()
    data = serializers.serialize("json", objs, sort_keys=True, indent=1)
    fh = open('fixtures/' + filename + '.json', 'w')
    fh.write(data)
    fh.close()
    done = time.time()

Example 26

Project: colab Source File: utils.py
Function: init
    def __init__(self, object, is_iterable = True):
        if is_iterable:
            content = serialize('xml', object)
        else:
            content = object
        super(XMLResponse, self).__init__(content, mimetype='application/xml')

Example 27

Project: django-mysql Source File: test_settextfield.py
Function: test_dumping
    def test_dumping(self):
        big_set = {six.text_type(i ** 2) for i in six.moves.range(1000)}
        instance = BigCharSetModel(field=big_set)
        data = json.loads(serializers.serialize('json', [instance]))[0]
        field = data['fields']['field']
        assert sorted(field.split(',')) == sorted(big_set)

Example 28

Project: shuup Source File: edit.py
Function: encode_address
def encode_address(address, tax_number=""):
    if not address:
        return {"tax_number": tax_number}
    address_dict = json.loads(serializers.serialize("json", [address]))[0].get("fields")
    if not address_dict.get("tax_number", ""):
        address_dict["tax_number"] = tax_number
    return address_dict

Example 29

Project: django-socialnews Source File: users.py
@login_required
def liked_links_secret(request, username, secret_key):
    user = User.objects.get(username = username)
    if not user.get_profile().secret_key == secret_key:
        raise Http404
    votes = LinkVote.objects.get_user_data().filter(user = request.user, direction = True).select_related()[:10]
    votes_id = [vote.link_id for vote in votes]
    links = Link.objects.filter(id__in = votes_id)
    return HttpResponse(serializers.serialize('json', links))

Example 30

Project: pythondotorg Source File: dump_pep_pages.py
    def handle_noargs(self, **options):
        qs = Page.objects.filter(path__startswith='peps/')

        serializers.serialize(
            format='json',
            queryset=qs,
            indent=4,
            stream=self.stdout,
        )

Example 31

Project: django-riv Source File: serializers.py
    def testSerializeChoiceExtraTwoObjects(self):
        self.choice1.observer = 'Mr. James'
        xmlstring = '<?xml version="1.0" encoding="utf-8"?><objects><choice><observer>%s</observer><votes>%d</votes><poll>%d</poll><id>%d</id><choice>%s</choice></choice><choice><votes>%d</votes><poll>%d</poll><id>%d</id><choice>%s</choice></choice></objects>' % (self.choice1.observer, self.choice1.votes, self.choice1.poll.id, self.choice1.id, self.choice1.choice, self.choice2.votes, self.choice2.poll.id, self.choice2.id, self.choice2.choice)
        result_xml = ET.fromstring(xmlstring)
        serialized_xml = ET.fromstring(serializers.serialize('restxml', [self.choice1, self.choice2], extra=['observer']))
        self.assertTrue(xml_compare(result_xml, serialized_xml))

Example 32

Project: memopol2 Source File: views.py
@staff_member_required
def moderation_get_unmoderated_positions(request):
    if not request.is_ajax():
        return HttpResponseServerError()

    last_id = request.GET[u'last_id']
    positions =  Position.objects.filter(moderated=False, id__gt=last_id)
    return HttpResponse(serializers.serialize('json', positions), mimetype='application/json')

Example 33

Project: django-compositepks Source File: tests.py
def fieldsTest(format, self):
    # Clear the database first
    management.call_command('flush', verbosity=0, interactive=False)

    obj = ComplexModel(field1='first',field2='second',field3='third')
    obj.save_base(raw=True)

    # Serialize then deserialize the test database
    serialized_data = serializers.serialize(format, [obj], indent=2, fields=('field1','field3'))
    result = serializers.deserialize(format, serialized_data).next()

    # Check that the deserialized object contains data in only the serialized fields.
    self.assertEqual(result.object.field1, 'first')
    self.assertEqual(result.object.field2, '')
    self.assertEqual(result.object.field3, 'third')

Example 34

Project: probr-core Source File: models.py
def publishPostSaveMessageDevice(sender, instance, created, **kwargs):
    payload = serializers.serialize('json', [instance, ])
    struct = json.loads(payload)
    struct[0]['fields']['object_type'] = instance._meta.verbose_name + ':update'
    struct[0]['fields']['apikey'] = instance.apikey # also send apikey
    payload = json.dumps(struct[0]['fields'])

    # also publish to foreign key fields, to enable grouping/filtering on client-side
    # for field in instance._meta.fields:
    #    if field.get_internal_type() == "ForeignKey":
    #        group = field.name + '-' + getattr(instance, field.name).uuid
    #        publishMessage(instance._meta.verbose_name_plural, message=payload, groups=[group])

    publishMessage("socket", message=payload)

Example 35

Project: channels Source File: websockets.py
Function: serialize_data
    def serialize_data(self, instance):
        """
        Serializes model data into JSON-compatible types.
        """
        if self.fields is not None:
            if self.fields == '__all__' or list(self.fields) == ['__all__']:
                fields = None
            else:
                fields = self.fields
        else:
            fields = [f.name for f in instance._meta.get_fields() if f.name not in self.exclude]
        data = serializers.serialize('json', [instance], fields=fields)
        return json.loads(data)[0]['fields']

Example 36

Project: extdirect.django Source File: store.py
Function: serialize
    def serialize(self, queryset, metadata=True, total=None):        
        meta = {
            'root': self.root,
            'total' : self.total,
            'success': self.success,
            'idProperty': self.id_property
        }        
        res = serialize('extdirect', queryset, meta=meta, extras=self.extras,
                        total=total, exclude_fields=self.exclude_fields)
        
        if metadata and self.metadata:            
            res['metaData'] = self.metadata        
        
        return res

Example 37

Project: djangotoolbox Source File: tests.py
    def test_json_setfield(self):
        for i in range(1, 5):
            SerializableSetModel(
                setfield=set([i - 1]),
                setcharfield=set(SerializationTest.names[:i])).save()
        objects = SerializableSetModel.objects.all()
        serialized = serializers.serialize('json', objects)
        deserialized = serializers.deserialize('json', serialized)
        for m in deserialized:
            integer = m.object.setfield.pop()
            names = m.object.setcharfield
            self.assertEqual(names, set(SerializationTest.names[:integer + 1]))

Example 38

Project: python-semanticversion Source File: test_django.py
Function: test_serialization
    def test_serialization(self):
        o1 = models.VersionModel(version=Version('0.1.1'), spec=Spec('==0.1.1,!=0.1.1-alpha'))
        o2 = models.VersionModel(version=Version('0.4.3-rc3+build3'),
            spec=Spec('<=0.1.1-rc2,!=0.1.1-rc1'))

        data = serializers.serialize('json', [o1, o2])

        obj1, obj2 = serializers.deserialize('json', data)
        self.assertEqual(o1.version, obj1.object.version)
        self.assertEqual(o1.spec, obj1.object.spec)
        self.assertEqual(o2.version, obj2.object.version)
        self.assertEqual(o2.spec, obj2.object.spec)

Example 39

Project: django-pgjson Source File: tests.py
Function: test_value_to_string_serializes_correctly
    def test_value_to_string_serializes_correctly(self):
        obj = self.model_class.objects.create(data={"a": 1})

        serialized_obj = serialize('json', self.model_class.objects.filter(pk=obj.pk))
        obj.delete()

        deserialized_obj = list(deserialize('json', serialized_obj))[0]

        obj = deserialized_obj.object
        obj.save()
        obj = obj.__class__.objects.get(pk=obj.pk)

        self.assertEqual(obj.data, {"a": 1})

Example 40

Project: django-multi-gtfs Source File: test_frequency.py
    def test_serialize(self):
        '''Test serialization of Frequency, which has a SecondsField'''
        f = Frequency.objects.create(
            trip=self.trip, start_time='05:00', end_time='25:00',
            headway_secs=1800)
        actual = loads(serialize('json', Frequency.objects.all()))
        expected = [{
            u"pk": f.id,
            u"model": u"multigtfs.frequency",
            u"fields": {
                u"exact_times": u"",
                u"extra_data": u"{}",
                u"start_time": u"05:00:00",
                u"headway_secs": 1800,
                u"trip": self.trip.id,
                u"end_time": u"25:00:00"}}]
        self.maxDiff = None
        self.assertEqual(expected, actual)

Example 41

Project: django-pgjson Source File: tests.py
Function: test_indent
        def test_indent(self):
            obj1 = TextModelWithIndent.objects.create(
                data={"name": "foo", "bar": {"baz": 1}})
            qs = TextModelWithIndent.objects.filter(data__at_name="foo")
            serialized_obj1 = serialize('json', qs)
            self.assertIn('\n  "name":',
                          json.loads(serialized_obj1)[0]['fields']['data'])

Example 42

Project: silver Source File: test_provider.py
    def test_POST_bulk_providers(self):
        providers = ProviderFactory.create_batch(5)

        raw_providers = json.loads(serializers.serialize('json', providers))

        serialized_providers = []
        for item in raw_providers:
            serialized_providers.append(item['fields'])

        url = reverse('provider-list')
        response = self.client.post(url, data=json.dumps(serialized_providers, ensure_ascii=True).encode('utf8'),
                                    content_type='application/json')

        assert response.status_code == status.HTTP_201_CREATED
        assert len(response.data) == 5

Example 43

Project: django-moderation Source File: fields.py
Function: serialize
    def _serialize(self, value):
        if not value:
            return ''

        value_set = [value]
        if value._meta.parents:
            value_set += [getattr(value, f.name)
                          for f in list(value._meta.parents.values())
                          if f is not None]

        return serializers.serialize(self.serialize_format, value_set)

Example 44

Project: kubernetes_django_postgres_redis Source File: views.py
Function: messages
def messages(request):
    """ REST endpoint providing basic operations. GET will return the list of
    all messages created so far in JSON form, POST will add a new message to
    the list of messages (guestbook).
    """
    if request.method == 'GET':
        data = serializers.serialize("json", Message.objects.all())
        return HttpResponse(data)
    elif request.method == 'POST':
        Message.objects.create(text=request.body)
        return HttpResponse(request.body)
    else:
        return HttpResponse("Unsupported HTTP Verb.")

Example 45

Project: readthedocs.org Source File: backend.py
Function: get_data
    def get_data(self, node_id, username, moderator=None):
        try:
            node = DocuementNode.objects.get(snapshots__hash=node_id)
        except DocuementNode.DoesNotExist:
            return None
        ret_comments = []
        for comment in node.comments.all():
            json_data = json.loads(serializers.serialize("json", [comment]))[0]
            fields = json_data['fields']
            fields['pk'] = json_data['pk']
            ret_comments.append(
                fields
            )

        return {'source': '',
                'comments': ret_comments}

Example 46

Project: OwnTube Source File: views.py
Function: search_json
def search_json(request):
    ''' The search view for handling the search using Django's "Q"-class (see normlize_query and get_query)'''
    query_string = ''
    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']

        entry_query = get_query(query_string, ['title', 'description','tags__name'])

        found_entries = Video.objects.filter(entry_query).order_by('-date')

    data = serializers.serialize('json', found_entries)
    return HttpResponse(data, content_type = 'application/javascript; charset=utf8')

Example 47

Project: django-synctool Source File: routing.py
def serialize_querysets(querysets):
    if not type(querysets) in (list, tuple):
        querysets = [querysets]

    def get_objects():
        for queryset in querysets:
            for obj in queryset:
                yield obj

    return serialize("json", get_objects())

Example 48

Project: pyjs Source File: jsonrpc.py
Function: json_convert
def json_convert(l, fields=None):
    res = []
    for i in l:
        item = serialize('python', [i], fields=fields)[0]
        if fields:
            for f in fields:
                if not item['fields'].has_key(f):
                    lg = open("/tmp/field.txt", "a")
                    lg.write("%s %s %s\n" % (repr(item), repr(f), repr(type(getattr(i, str(f))))))
                    lg.close()
                    item['fields'][f] = json_convert([getattr(i, f)], )[0]
        res.append(dict_datetimeflatten(item))
    return res

Example 49

Project: django-picklefield Source File: tests.py
Function: test_serialization
    def testSerialization(self):
        model_test = MinimalTestingModel(pickle_field={'foo': 'bar'})
        json_test = serializers.serialize('json', [model_test])
        self.assertEquals(json_test,
                          '[{"pk": null,'
                          ' "model": "picklefield.minimaltestingmodel",'
                          ' "fields": {"pickle_field": "gAJ9cQFVA2Zvb3ECVQNiYXJxA3Mu"}}]')
        for deserialized_test in serializers.deserialize('json', json_test):
            self.assertEquals(deserialized_test.object,
                              model_test)

Example 50

Project: colab Source File: utils.py
Function: init
    def __init__(self, object, is_iterable = True):
        if is_iterable:
            content = serialize('json', object)
        else:
            content = simplejson.dumps(object, cls=LazyEncoder)
        super(JSONResponse, self).__init__(content, mimetype='application/json')
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4