Python django.core.serializers.serialize() Examples

The following are 30 code examples of django.core.serializers.serialize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.serializers , or try the search function .
Example #1
Source File: ajax_views.py    From djangoSIGE with MIT License 7 votes vote down vote up
def post(self, request, *args, **kwargs):
        obj_list = []
        pessoa = Pessoa.objects.get(pk=request.POST['pessoaId'])
        cliente = Cliente.objects.get(pk=request.POST['pessoaId'])
        obj_list.append(cliente)

        if pessoa.endereco_padrao:
            obj_list.append(pessoa.endereco_padrao)
        if pessoa.email_padrao:
            obj_list.append(pessoa.email_padrao)
        if pessoa.telefone_padrao:
            obj_list.append(pessoa.telefone_padrao)

        if pessoa.tipo_pessoa == 'PJ':
            obj_list.append(pessoa.pessoa_jur_info)
        elif pessoa.tipo_pessoa == 'PF':
            obj_list.append(pessoa.pessoa_fis_info)

        data = serializers.serialize('json', obj_list, fields=('indicador_ie', 'limite_de_credito', 'cnpj', 'inscricao_estadual', 'responsavel', 'cpf', 'rg', 'id_estrangeiro', 'logradouro', 'numero', 'bairro',
                                                               'municipio', 'cmun', 'uf', 'pais', 'complemento', 'cep', 'email', 'telefone',))

        return HttpResponse(data, content_type='application/json') 
Example #2
Source File: ajax_views.py    From djangoSIGE with MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        obj_list = []
        pessoa = Pessoa.objects.get(pk=request.POST['pessoaId'])
        fornecedor = Fornecedor.objects.get(pk=request.POST['pessoaId'])
        obj_list.append(fornecedor)

        if pessoa.endereco_padrao:
            obj_list.append(pessoa.endereco_padrao)
        if pessoa.email_padrao:
            obj_list.append(pessoa.email_padrao)
        if pessoa.telefone_padrao:
            obj_list.append(pessoa.telefone_padrao)

        if pessoa.tipo_pessoa == 'PJ':
            obj_list.append(pessoa.pessoa_jur_info)
        elif pessoa.tipo_pessoa == 'PF':
            obj_list.append(pessoa.pessoa_fis_info)

        data = serializers.serialize('json', obj_list, fields=('indicador_ie', 'limite_de_credito', 'cnpj', 'inscricao_estadual', 'responsavel', 'cpf', 'rg', 'id_estrangeiro', 'logradouro', 'numero', 'bairro',
                                                               'municipio', 'cmun', 'uf', 'pais', 'complemento', 'cep', 'email', 'telefone',))

        return HttpResponse(data, content_type='application/json') 
Example #3
Source File: tests.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def SpiderAPI(request):
        pass
        # all = TweetsInfo.objects.filter(UserInfo_id=text)
        # for e in all:
        #     mm = ()
        #     s = SnowNLP(e.Content.replace('转发理由','').replace('转发内容', '').replace('原始用户', '').replace('转发微博已被删除', ''))
        #     for i in s.tags:
        #         mm += i
        #     TweetsInfo.objects.filter(_id=e._id).update(tags=s.keywords(5))
        #     TweetsInfo.objects.filter(_id=e._id).update(pinyin=mm)
        #     TweetsInfo.objects.filter(_id=e._id).update(sentiments=str(s.sentiments))
        #     print(s.keywords(5))
        # else:
        #     text = "输入微博Id错误,请重新输入!"
        #     res['ok'] = text
        # try:
        # resp = Target.objects.values('uid','cookie','add_time')
        # resp = json.dumps(resp,cls=JsonCustomEncoder)
        # resp = serializers.serialize("json", Target.objects.all().order_by("-id")[:1])
        # wb = Weibo(uid,cookie)
        # mm = wb.get_comment_info('4358934418168720')
        # mm = wb.get_weibo_info()
        # mm = wb.getTest()
        # except Exception as e:
        #     return HttpResponse('拉取数据库数据失败: %s' % e) 
Example #4
Source File: views.py    From property-finder with Apache License 2.0 6 votes vote down vote up
def properties_geojson(request):
    """
    Retrieves properties given the querystring params, and 
    returns them as GeoJSON.
    """
    ne = request.GET["ne"].split(",")
    sw = request.GET["sw"].split(",")
    lookup = {
        "point__contained": Polygon.from_bbox((sw[1], sw[0], ne[1], ne[0])),
        "bedrooms__gte": request.GET["min-bedrooms"],
        "bedrooms__lte": request.GET["max-bedrooms"],
        "bathrooms__gte": request.GET["min-bathrooms"],
        "car_spaces__gte": request.GET["min-car-spaces"],
        "property_type__in": request.GET["property-types"].split(",")
    }
    if request.GET["nearest-school"] != "1":
        lookup["nearest_school_distance__lt"] = int(request.GET["nearest-school"]) - 1
    if request.GET["nearest-train-station"] != "1":
        lookup["nearest_train_station_distance__lt"] = int(request.GET["nearest-train-station"]) - 1

    properties = Property.objects.filter(**lookup)
    json = serialize("geojson", properties, geometry_field="point")

    return HttpResponse(json, content_type="application/json") 
Example #5
Source File: model_anonymizers.py    From django-GDPR with MIT License 6 votes vote down vote up
def _perform_version_update(version, update_data):
        from reversion import revisions
        if hasattr(version, "object_version"):
            local_obj = version.object_version.object
        else:
            local_obj = version._object_version.object
        for field, value in update_data.items():
            setattr(local_obj, field, value)
        if hasattr(revisions, '_get_options'):
            version_options = revisions._get_options(get_reversion_version_model(version))
            version_format = version_options.format
            version_fields = version_options.fields
        else:
            version_adapter = revisions.get_adapter(get_reversion_version_model(version))
            version_format = version_adapter.get_serialization_format()
            version_fields = list(version_adapter.get_fields_to_serialize())
        version.serialized_data = serializers.serialize(
            version_format,
            (local_obj,),
            fields=version_fields
        )
        version.save() 
Example #6
Source File: api.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def command(request):
    data = json.loads(request.POST.get('data', '{}'))
    func = getattr(commands, data['command'], None)
    if func:
        if request.user.has_perm(func.permission):
            output, status = func(data)
            output = serializers.serialize('json', output, ensure_ascii=False)
        else:
            output = json.dumps({'error': 'permission denied'})
            status = 403
    else:
        output = json.dumps({'error': 'unrecognized command'})
        status = 400
    resp = HttpResponse(output, content_type='application/json;charset=utf-8')
    if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
        return HttpResponse(
            json.dumps(connection.queries, ensure_ascii=False, indent=1),
            status=status,
            content_type='application/json;charset=utf-8',
        )
    return resp 
Example #7
Source File: tests.py    From django-versatileimagefield with MIT License 6 votes vote down vote up
def test_field_serialization(self):
        """Ensure VersatileImageField and PPOIField serialize correctly."""
        output = serializers.serialize(
            'json',
            VersatileImageTestModel.objects.filter(img_type='png')
        )
        self.assertJSONEqual(
            output,
            [
                {
                    "fields": {
                        "img_type": "png",
                        "ppoi": "0.5x0.5",
                        "width": 601,
                        "height": 203,
                        "image": "python-logo.png",
                        "optional_image_3": "",
                        "optional_image_2": "",
                        "optional_image": "python-logo.jpg"
                    },
                    "model": "tests.versatileimagetestmodel",
                    "pk": self.png.pk
                }
            ]
        ) 
Example #8
Source File: test_model_integrations.py    From django-enum-choices with MIT License 5 votes vote down vote up
def test_serialization(self):
        IntegerEnumeratedModel.objects.create(
            enumeration=IntTestEnum.FIRST
        )

        data = serializers.serialize('json', IntegerEnumeratedModel.objects.all())

        expected = '[{"model": "testapp.integerenumeratedmodel", "pk": 1, "fields": {"enumeration": "1"}}]'

        self.assertEqual(expected, data) 
Example #9
Source File: serialization.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def json_serialize(objects):
    """
        Serializes by removing the fields property from serialization in favor of a flatter dictionary
    """
    # this gives you a list of dicts
    raw_data = serializers.serialize('python', objects)
    # now extract the inner `fields` dicts
    actual_data = cond_deep_flat_map_iterable(raw_data)
    # and now dump to JSON
    return json.dumps(actual_data) 
Example #10
Source File: middleware.py    From robotframework-djangolibrary with Apache License 2.0 5 votes vote down vote up
def model_to_dict(model):
    serialized_obj = serializers.serialize('python', [model])
    serialized_obj = serialized_obj[0]
    serialized_obj = dict(serialized_obj)
    for key, value in serialized_obj.items():
        if isinstance(value, OrderedDict):
            serialized_obj[key] = dict(value)
    serialized_obj = serialized_obj['fields']
    serialized_obj['id'] = model.id
    serialized_obj['pk'] = model.pk
    return serialized_obj 
Example #11
Source File: creation.py    From python with Apache License 2.0 5 votes vote down vote up
def serialize_db_to_string(self):
        """
        Serializes all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (model._meta.can_migrate(self.connection) and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    for obj in queryset.iterator():
                        yield obj
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue() 
Example #12
Source File: app_dump.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_model_fixture_dump(app_name, model_name, filter_options=None, indent=4):
    """
    Get Model objects dump
    :param app_name:
    :param model_name:
    :param filter_options:
    :return:
    """
    app_module = sys.modules['apps.{}.models'.format(app_name)]
    model = getattr(app_module, model_name)
    queryset = model.objects.all()
    if filter_options:
        queryset = queryset.filter(**filter_options)
    return core_serializers.serialize('json', queryset, indent=indent or None) 
Example #13
Source File: app_dump.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_field_values_dump() -> str:
    import apps.document.repository.document_field_repository as dfr
    field_repo = dfr.DocumentFieldRepository()
    data = field_repo.get_annotated_values_for_dump()
    transfer_objects = [ExternalFieldValue(**i) for i in data]
    return core_serializers.serialize('json', transfer_objects) 
Example #14
Source File: app_dump.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_dump(filter_by_model: Dict[Type[Model], Callable] = None,
             object_handler_by_model: dict = None) -> str:
    object_handler_by_model = object_handler_by_model if object_handler_by_model is not None else {}
    objects = []
    for model, qs_filter in filter_by_model.items():
        handler = object_handler_by_model.get(model) or default_object_handler
        query_set = qs_filter(model.objects.get_queryset()) if qs_filter else model.objects.all()
        objects += [handler(obj) for obj in query_set]
    return core_serializers.serialize('json', objects) 
Example #15
Source File: creation.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def serialize_db_to_string(self):
        """
        Serialize all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (model._meta.can_migrate(self.connection) and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    yield from queryset.iterator()
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue() 
Example #16
Source File: sites.py    From django-admino with MIT License 5 votes vote down vote up
def obj_as_dict(self, request, obj):
        data = self.serialize_obj(obj)

        # serialize model instance fields datas
        for field in obj._meta.get_fields():
            if field.is_relation and field.concrete:
                field_value = getattr(obj, field.name)
                if field_value:
                    if field.many_to_many:
                        data[field.name] = self.serialize_objs(field_value.all())
                    elif field.many_to_one or field.one_to_one or field.one_to_many:
                        data[field.name] = self.serialize_obj(field_value)

        # add custom admin class field to serialized bundle
        model_admin_fields = self.get_model_admin_field_names(request, obj)
        for field in model_admin_fields:
            if field in data:
                continue

            if hasattr(obj, field):
                f = getattr(obj, field)
                data[field] = unicode(f)

            if hasattr(self, field):
                field_method = getattr(self, field)
                if callable(field_method):
                    data[field] = field_method(obj)
                else:
                    data[field] = field_method

        info = self.model._meta.app_label, self.model._meta.model_name
        admin_detail_url = str(reverse_lazy("admin:%s_%s_change" % info, args=(obj.id,)))
        data["admin_detail_url"] = admin_detail_url
        return data 
Example #17
Source File: sites.py    From django-admino with MIT License 5 votes vote down vote up
def serialize_objs(self, objs):
        data_objs = json.loads(serializers.serialize('json', objs))
        for data in data_objs:
            data.update(data["fields"])
            del data["fields"]
        return data_objs 
Example #18
Source File: test_hook_select_field.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_serialisation(self):
        hooks = ["do_foo", "do_bar"]
        obj = next(
            serializers.deserialize(
                "json", serializers.serialize("json", [HookSelectModel(hooks=hooks)])
            )
        ).object
        self.assertEqual(obj.hooks, hooks) 
Example #19
Source File: views.py    From notto with MIT License 5 votes vote down vote up
def html2pdf(request, note_name):
    """
    generate a pdf document
    """
    record = None
    try:
        notes = Note.objects.filter(
            url_title=note_name
        )
        if request.method == 'GET' and notes:
            record = notes[0]
        elif not notes:
            record = Note()
        children = serializers.serialize(
            'python', record.get_children().all(), fields=('url_title')
        )
        children = json.dumps([c['fields'] for c in children])
        pdf = render_to_pdf('template.html', {
            'pagesize': 'A4',
            'title': note_name,
            'mylist': record.content
        })
        return HttpResponse(pdf, content_type='application/pdf')

    except Note.DoesNotExist:
        record = Note(
            content='',
            url_title=note_name
        )
    pdf = render_to_pdf('template.html', {
        'pagesize': 'A4',
        'title': note_name,
        'mylist': ""
    })
    return HttpResponse(pdf, content_type='application/pdf') 
Example #20
Source File: models.py    From fermentrack with MIT License 5 votes vote down vote up
def save_to_redis(self, device_id: int=None):
        # This saves the current (presumably complete) object as the 'current' point to redis
        r = redis.Redis(host=settings.REDIS_HOSTNAME, port=settings.REDIS_PORT, password=settings.REDIS_PASSWORD)
        if device_id is None:
            if self.associated_log is not None:
                r.set('grav_{}_full'.format(self.associated_log.device_id), serializers.serialize('json', [self, ]).encode(encoding="utf-8"))
            elif self.associated_device is not None:
                r.set('grav_{}_full'.format(self.associated_device_id), serializers.serialize('json', [self, ]).encode(encoding="utf-8"))
            else:
                raise ReferenceError  # Not sure if this is the right error type, but running with it
        else:
            r.set('grav_{}_full'.format(device_id), serializers.serialize('json', [self, ]).encode(encoding="utf-8")) 
Example #21
Source File: creation.py    From bioforum with MIT License 5 votes vote down vote up
def serialize_db_to_string(self):
        """
        Serialize all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (model._meta.can_migrate(self.connection) and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    yield from queryset.iterator()
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue() 
Example #22
Source File: export_xforms_and_instances.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **kwargs):
        fixtures_dir = os.path.join(ONADATA_DIR, "json_xform_fixtures")
        if not os.path.exists(fixtures_dir):
            os.mkdir(fixtures_dir)

        xform_fp = os.path.join(fixtures_dir, "a-xforms.json")
        instance_fp = os.path.join(fixtures_dir, "b-instances.json")

        xfp = open(xform_fp, 'w')
        xfp.write(serialize("json", XForm.objects.all()))
        xfp.close()

        ifp = open(instance_fp, 'w')
        ifp.write(serialize("json", Instance.objects.all()))
        ifp.close() 
Example #23
Source File: models.py    From REST-API with MIT License 5 votes vote down vote up
def serialize(self):
        try:
            image = self.image.url
        except:
            image = ""            
        data = {
            "id": self.id,
            "content": self.content,
            "user": self.user.id,
            "image": image
        }
        data = json.dumps(data)
        return data 
Example #24
Source File: models.py    From REST-API with MIT License 5 votes vote down vote up
def serialize(self):
        list_values = list(self.values("user", "content", "image", "id"))
        return json.dumps(list_values) 
Example #25
Source File: ajax_views.py    From djangoSIGE with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        obj_list = []
        pro = Produto.objects.get(pk=request.POST['produtoId'])
        obj_list.append(pro)

        if pro.grupo_fiscal:
            if pro.grupo_fiscal.regime_trib == '0':
                icms, created = ICMS.objects.get_or_create(
                    grupo_fiscal=pro.grupo_fiscal)
            else:
                icms, created = ICMSSN.objects.get_or_create(
                    grupo_fiscal=pro.grupo_fiscal)

            ipi, created = IPI.objects.get_or_create(
                grupo_fiscal=pro.grupo_fiscal)
            icms_dest, created = ICMSUFDest.objects.get_or_create(
                grupo_fiscal=pro.grupo_fiscal)
            obj_list.append(icms)
            obj_list.append(ipi)
            obj_list.append(icms_dest)

        data = serializers.serialize('json', obj_list, fields=('venda', 'controlar_estoque', 'estoque_atual',
                                                               'tipo_ipi', 'p_ipi', 'valor_fixo', 'p_icms', 'p_red_bc', 'p_icmsst', 'p_red_bcst', 'p_mvast',
                                                               'p_fcp_dest', 'p_icms_dest', 'p_icms_inter', 'p_icms_inter_part',
                                                               'ipi_incluido_preco', 'incluir_bc_icms', 'incluir_bc_icmsst', 'icmssn_incluido_preco',
                                                               'icmssnst_incluido_preco', 'icms_incluido_preco', 'icmsst_incluido_preco'))
        return HttpResponse(data, content_type='application/json') 
Example #26
Source File: ajax_views.py    From djangoSIGE with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        veiculos = Transportadora.objects.get(
            pk=request.POST['transportadoraId']).veiculo.all()
        data = serializers.serialize(
            'json', veiculos, fields=('id', 'descricao',))

        return HttpResponse(data, content_type='application/json') 
Example #27
Source File: ajax_views.py    From djangoSIGE with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        pessoa = Pessoa.objects.get(pk=request.POST['pessoaId'])
        obj_list = []
        obj_list.append(pessoa.pessoa_jur_info)

        if pessoa.endereco_padrao:
            obj_list.append(pessoa.endereco_padrao)

        data = serializers.serialize('json', obj_list, fields=('cnpj', 'inscricao_estadual', 'logradouro', 'numero', 'bairro',
                                                               'municipio', 'cmun', 'uf', 'pais', 'complemento', 'cep',))

        return HttpResponse(data, content_type='application/json') 
Example #28
Source File: models.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def log_change(self, user, request_id, action):
        """
        Creates a new ObjectChange representing a change made to this object.
        """
        ObjectChange(
            user=user,
            request_id=request_id,
            changed_object=self,
            action=action,
            object_data=self.serialize(),
        ).save() 
Example #29
Source File: api.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request):
    from servo.models import Status
    results = Status.objects.all()
    data = serialize('json', results)
    return HttpResponse(data, content_type='application/json') 
Example #30
Source File: models.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def serialize(self):
        """
        Returns a JSON representation of an object using Django's built-in serializer.
        """
        return json.loads(serialize("json", [self]))[0]["fields"]