Python django.core.serializers.serialize() Examples

The following are 30 code examples for showing how to use django.core.serializers.serialize(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.serializers , or try the search function .

Example 1
Project: djangoSIGE   Author: thiagopena   File: ajax_views.py    License: 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
Project: donation-tracker   Author: GamesDoneQuick   File: api.py    License: 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 3
Project: property-finder   Author: googlemaps   File: views.py    License: 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 4
Project: djangoSIGE   Author: thiagopena   File: ajax_views.py    License: 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 5
Project: weibo-analysis-system   Author: Superbsco   File: tests.py    License: 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 6
Project: django-GDPR   Author: druids   File: model_anonymizers.py    License: 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 7
Project: django-versatileimagefield   Author: respondcreate   File: tests.py    License: 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
Project: Servo   Author: fpsw   File: api.py    License: 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 9
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def locations(request):
    queryset = Location.objects.all()
    serializer = 'json'
    if request.META['HTTP_USER_AGENT'].startswith('curl'):
        serializer = 'yaml'
    data = serialize(serializer, queryset)
    return HttpResponse(data) 
Example 10
Project: Servo   Author: fpsw   File: api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def queues(request):
    queryset = Queue.objects.all()
    data = serialize('json', queryset, fields=('pk', 'title'))
    return HttpResponse(data, content_type='application/json') 
Example 11
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def list_members(self, request, *args, **kwargs):
        """
        List all members of this project.
        """
        project = self.get_object()
        users = project.members.all()
        data = serializers.serialize("json", users)

        return Response(json.loads(data), status=status.HTTP_200_OK) 
Example 12
Project: coursys   Author: sfu-fas   File: devtest_importer.py    License: GNU General Public License v3.0 5 votes vote down vote up
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()
    #print "(%.1f s)" % (done-start) 
Example 13
Project: coursys   Author: sfu-fas   File: load_demo_data.py    License: GNU General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        assert settings.DEPLOY_MODE != 'production'
        raise NotImplementedError()

        n_fake = 200
        fake_students = [Person(
            emplid=str(500000000 + i),
            userid='fake%03i' % (i,),
            last_name='Fake',
            first_name=random_name(8),
            middle_name=random_name(5),
            title=random.choice(['Mr', 'M', 'Ms', 'Dr', 'Count'])
        ) for i in range(n_fake)]
        for p in fake_students:
            p.pref_first_name = random.choice([None, p.first_name[:4]])

        students_per_class = 10
        for o in CourseOffering.objects.all():
            student_people = random.choices(fake_students, k=students_per_class)
            student_members = [
                Member(person=p, offering=o, role='STUD', added_reason='AUTO', credits=3, career='UGRD')
                for p in student_people
            ]
            data.append(student_members)


        print(serializers.serialize('json', itertools.chain(*data), indent=2)) 
Example 14
Project: vulscan   Author: vulscanteam   File: views.py    License: MIT License 5 votes vote down vote up
def poc_list_json(request):
    data = models.poc_list.objects.all()
    #print help(data.__dict__) #内置数据库对象 转为 字典类型
    #获取数据库的poc列表
    #print local_json
    response_json = serializers.serialize("json", data)
    #print response_json
    return HttpResponse(response_json)


    """
    |  appName = <django.db.models.query_utils.DeferredAttribute object>
    |  appPowerLink = <django.db.models.query_utils.DeferredAttribute object>
    |  appVersion = <django.db.models.query_utils.DeferredAttribute object>
    |  author = <django.db.models.query_utils.DeferredAttribute object>
    |  category = <django.db.models.query_utils.DeferredAttribute object>
    |  createDate = <django.db.models.query_utils.DeferredAttribute object>
    |  desc = <django.db.models.query_utils.DeferredAttribute object>
    |  filename = <django.db.models.query_utils.DeferredAttribute object>
    |  install_requires = <django.db.models.query_utils.DeferredAttribute object>
    |  name = <django.db.models.query_utils.DeferredAttribute object>
    |  objects = <django.db.models.manager.Manager object>
    |  references = <django.db.models.query_utils.DeferredAttribute object>
    |  samples = <django.db.models.query_utils.DeferredAttribute object>
    |  updateDate = <django.db.models.query_utils.DeferredAttribute object>
    |  version = <django.db.models.query_utils.DeferredAttribute object>
    |  vulID = <django.db.models.query_utils.DeferredAttribute object>
    |  vulType = <django.db.models.query_utils.DeferredAttribute object>
    """

#客户端和服务端重用api 
Example 15
Project: onehome-server   Author: michwh   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request):
        if request.user.is_authenticated:

            # data = request.data
            key = request.GET.get('key')
            search_list = Product.objects.filter(title__contains=key)
            # paginator = Paginator(search_list, 5)
            # try:
            #     search = paginator.page(data.get('page'))
            # except PageNotAnInteger:
            #     search = paginator.page(1)
            # except EmptyPage:
            #     search = paginator.page(paginator.num_pages)
            # # print(search)
            # search_list = json.loads(serializers.serialize("json", search_list))
            ser = ProductSerializer(instance=search_list, many=True)
            # print(ser.data)
            msg = sort_out_list(request, ser.data)
            return Response(msg, 200)
        else:
            msg = {
                'stateCode': 201,
                'msg': '没有访问权限'
            }
            return Response(msg, 201)


# 获取我的发布列表 
Example 16
Project: jsgrid-django   Author: tabalinas   File: views.py    License: MIT License 5 votes vote down vote up
def to_json(self, objects):
        return serializers.serialize('json', objects) 
Example 17
Project: GTDWeb   Author: lanbing510   File: creation.py    License: GNU General Public License v2.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 (not model._meta.proxy and model._meta.managed 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 18
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def serialize(format, queryset, **options):
    """
    Serialize a queryset (or any iterator that returns database objects) using
    a certain serializer.
    """
    s = get_serializer(format)()
    s.serialize(queryset, **options)
    return s.getvalue() 
Example 19
Project: readux   Author: ecds   File: tests.py    License: MIT License 5 votes vote down vote up
def test_manifest_for_collection_serializer(self):
        manifest = json.loads(serialize('collection_manifest', Manifest.objects.all(), is_list = True))
        assert manifest[0]['@type'] == 'sc:Manifest'
        assert isinstance(manifest, list) 
Example 20
Project: readux   Author: ecds   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(serialize('canvas', self.get_queryset(), is_list=True)), safe=False) 
Example 21
Project: readux   Author: ecds   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(serialize('canvas', self.get_queryset())))
        
# TODO It should be okay to remove this.
# class StartingCanvas(View):
#     def get_queryset(self):
#         return Canvas.objects.filter(is_starting_page=True)

#     def get(self, request, *args, **kwargs):
#         return JsonResponse(json.loads(serialize('startingcanvas', self.get_queryset(), is_list=True)), safe=False) 
Example 22
Project: readux   Author: ecds   File: kollection.py    License: MIT License 5 votes vote down vote up
def get_dump_object(self, obj):
        if ((self.version == 'v2') or (self.version is None)):
            data = {
              "@context": "http://iiif.io/api/presentation/2/context.json",
              "@id": "%s/iiif/%s/%s/collection" % (settings.HOSTNAME, self.version, obj.pid),
              "@type": "sc:Collection",
              "label": obj.label,
              "viewingHint": "top",
              "description": obj.summary,
              "attribution": obj.attribution,
              "manifests": json.loads(serialize('collection_manifest', obj.manifests.all(), is_list=True))
            }
            return data 
Example 23
Project: readux   Author: ecds   File: annotation_list.py    License: MIT License 5 votes vote down vote up
def get_dump_object(self, obj):
        if ((self.version == 'v2') or (self.version is None)):
            data = {
                "@context": "http://iiif.io/api/presentation/2/context.json",
                "@id": "%s/iiif/v2/%s/list/%s" % (settings.HOSTNAME, obj.manifest.pid, obj.pid),
                "@type": "sc:AnnotationList",
                "resources": json.loads(serialize('annotation', obj.annotation_set.filter(Q(owner=User.objects.get(username='ocr')) | Q(owner__in=self.owners)), is_list=True))
            }
            return data 
Example 24
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_integer_dumping(self):
        instance = EncryptedIntegerModel(field=42)
        data = serializers.serialize('json', [instance])
        self.assertEqual(json.loads(self.test_data_integer), json.loads(data)) 
Example 25
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_char_dumping(self):
        instance = EncryptedCharModel(field='Hello, world!')
        data = serializers.serialize('json', [instance])
        self.assertEqual(json.loads(self.test_data_char), json.loads(data)) 
Example 26
Project: django-cryptography   Author: georgemarshall   File: test_pickle.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dumping(self):
        instance = PickledModel(field=[1, 2, None])
        data = serializers.serialize('json', [instance])
        self.assertEqual(json.loads(self.test_data), json.loads(data)) 
Example 27
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def update_comment(request, comment_id):
    c = get_object_or_404(Comments, pk=comment_id)
    i = c.incident
    if request.method == 'GET':
        if not request.user.has_perm('incidents.view_incidents', obj=i):
            ret = {'status': 'error', 'errors': ['Permission denied', ]}
            return HttpResponseServerError(dumps(ret), content_type="application/json")
        serialized = serializers.serialize('json', [c, ])
        return HttpResponse(dumps(serialized), content_type="application/json")
    else:
        comment_form = CommentForm(request.POST, instance=c)
        if not request.user.has_perm('incidents.handle_incidents', obj=i):
            comment_form.fields['action'].queryset = Label.objects.filter(group__name='action').exclude(
                name__in=['Closed', 'Opened', 'Blocked'])

        if comment_form.is_valid():

            c = comment_form.save()

            log("Comment edited: %s" % (comment_form.cleaned_data['comment'][:20] + "..."), request.user,
                incident=c.incident)

            if c.action.name in ['Closed', 'Opened', 'Blocked']:
                if c.action.name[0] != c.incident.status:
                    previous_status = c.incident.status
                    c.incident.status = c.action.name[0]
                    c.incident.save()
                    model_status_changed.send(sender=Incident, instance=c.incident, previous_status=previous_status)

            i.refresh_artifacts(c.comment)

            return render(request, 'events/_comment.html', {'comment': c, 'event': i})
        else:
            ret = {'status': 'error', 'errors': comment_form.errors}
            return HttpResponseServerError(dumps(ret), content_type="application/json")


# events ==================================================================== 
Example 28
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk):
        geo_layer = get_object_or_404(GeoLayer, id=pk)
        return JsonResponse(json.loads(serialize(
            'geojson',
            geo_layer.geo_areas.all(),
            geometry_field='geometry',
            fields=('id', 'title', 'code', 'geometry'),
        ))) 
Example 29
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        # dashboard_data = super(Organization_dashboard, self).get_context_data(**kwargs)
        obj = Organization.objects.get(pk=self.kwargs.get('pk'))
        peoples_involved = obj.organization_roles.filter(ended_at__isnull=True).distinct('user_id')
        sites = Site.objects.filter(project__organization=obj,is_survey=False, is_active=True)[:100]
        data = serialize('custom_geojson', sites, geometry_field='location',
                         fields=('name', 'public_desc', 'additional_desc', 'address', 'location', 'phone', 'id'))
        projects = Project.objects.filter(organization_id=obj.pk)
        total_projects = len(projects)
        total_sites = Site.objects.filter(project__organization=obj,is_survey=False, is_active=True).count()
        outstanding, flagged, approved, rejected = obj.get_submissions_count()
        bar_graph = {} #BarGenerator(sites)
        line_chart = [] #LineChartGeneratorOrganization(obj)
        line_chart_data = {} #line_chart.data()
        # user = User.objects.filter(pk=self.kwargs.get('pk'))
        roles_org = UserRole.objects.filter(organization_id = self.kwargs.get('pk'), project__isnull=True,
                                            site__isnull = True,
                                            ended_at__isnull=True)

        dashboard_data = {
            'obj': obj,
            'projects': projects,
            'sites': sites,
            'peoples_involved': peoples_involved,
            'total_projects': total_projects,
            'total_sites': total_sites,
            'outstanding': outstanding,
            'flagged': flagged,
            'approved': approved,
            'rejected': rejected,
            'data': data,
            'cumulative_data': [], #line_chart_data.values(),
            'cumulative_labels': [], #line_chart_data.keys(),
            'progress_data': [], #bar_graph.data.values(),
            'progress_labels': [] , #bar_graph.data.keys(),
            'roles_org': roles_org,
            'total_submissions': flagged + approved + rejected + outstanding,
        }
        return dashboard_data 
Example 30
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk):
        obj = Project.objects.get(pk=self.kwargs.get('pk'))
        organization = Organization.objects.get(pk=obj.organization_id)
        peoples_involved = obj.project_roles.filter(group__name__in=["Project Manager", "Reviewer"]).distinct('user')
        project_managers = obj.project_roles.select_related('user').filter(group__name__in=["Project Manager"]).distinct('user')

        sites = obj.sites.filter(is_active=True, is_survey=False)
        data = serialize('custom_geojson', sites, geometry_field='location',
                         fields=('name', 'public_desc', 'additional_desc', 'address', 'location', 'phone','id',))

        total_sites = len(sites)
        total_survey_sites = obj.sites.filter(is_survey=True).count()
        outstanding, flagged, approved, rejected = obj.get_submissions_count()
        bar_graph = BarGenerator(sites)

        line_chart = LineChartGenerator(obj)
        line_chart_data = line_chart.data()
        dashboard_data = {
            'sites': sites,
            'obj': obj,
            'peoples_involved': peoples_involved,
            'total_sites': total_sites,
            'total_survey_sites': total_survey_sites,
            'outstanding': outstanding,
            'flagged': flagged,
            'approved': approved,
            'rejected': rejected,
            'data': data,
            'cumulative_data': line_chart_data.values(),
            'cumulative_labels': line_chart_data.keys(),
            'progress_data': bar_graph.data.values(),
            'progress_labels': bar_graph.data.keys(),
            'project_managers':project_managers,
            'organization': organization,
            'total_submissions': line_chart_data.values()[-1],
    
        }
        return render(request, 'fieldsight/project_individual_submission_report.html', dashboard_data)