Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Django rest framework]: Serialize a list of strings

I am working with django and djando rest framework

I have created a new endpoint installedapps. When making GET requests to it, I want to return the data contained as a list of strings (list of installed apps)

The list of strings looks something like this:

installed_apps = ['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_js_reverse', 'djcelery', 'bootstrap3', 'foo', 'bar', 'apirest']

Until now I have only worked with model serializers, and everything was pretty easy. But now i dont know how to return this list of strings

This is what I have tried so far:

class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):
        from credits.views import GetInstalledApps

        installed_apps = GetInstalledApps.get_installed_apps()

        serializer = serializers.InstalledAppsSerializer(
            instance=installed_apps, many=True)

        return Response(serializer.data)




class InstalledAppsSerializer(serializers.ListField):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')

I am always getting all kind of errors. Any help on how to return the content of the list of strings?

Update

I have tried @e4c5 code, leaving it like this:

class InstalledAppsViewSet(viewsets.ViewSet):
    serializer_class = serializers.InstalledAppsSerializer

    def list(self, request):

        serializer = serializers.InstalledAppsSerializer


class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps = serializers.SerializerMethodField('get_the_installed_apps')


    def get_the_installed_apps(self):
        from credits.views import GetInstalledApps
        installed_apps = GetInstalledApps.get_installed_apps()

        return installed_apps

And I'm still getting errors. But I don't get the error message anywhere. Any help?

like image 696
Xar Avatar asked Jun 05 '17 10:06

Xar


People also ask

What is serialization in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is Validated_data?

validated_data is an OrderedDict and you can see it only after is_valid() and is_valid() == True.

What is HyperlinkedModelSerializer?

HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.


2 Answers

You could use the serializers.ListField,

ListField is a field class that validates a list of objects.

The ListField class also supports a declarative style that allows you to write reusable list field classes.

You could write a custom field for serializer inheriting from ListField form the drf serializers which accepts list of strings. Maybe like this, this example is already shown in the DRF docs.

class StringListField(serializers.ListField):
    child = serializers.CharField()

We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.

These are from the docs, I haven't tried it yet. But hope you get what you looking for.

You could use the custom field in your serializer like,

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = StringListField()
like image 173
zaidfazil Avatar answered Sep 25 '22 11:09

zaidfazil


it works for serialize a list of strings

class MySerializer(serializers.Serializer):
    installed_apps = serializers.ListSerializer(child=serializers.CharField())

it return

['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_js_reverse', 'djcelery', 'bootstrap3', 'foo', 'bar', 'apirest']
like image 38
Jonhatan Fajardo Avatar answered Sep 25 '22 11:09

Jonhatan Fajardo