[Django]-[Django rest framework]: Serialize a list of strings

27👍

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()

6👍

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']

2👍

The ‘all kinds of errors’ would probably go away if you based your serializer on a serializer, rather than a serializer field

ListField

A field class that validates a list of objects.

You might want to use it when one of the members of your class is a list. But you don’t want to ListField as a serializer, because it isn’t one

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')
👤e4c5

0👍

For the

And I’m still getting errors. But I don’t get the error message
anywhere.

part of the question: the error should be in the response you receive from the view after sending the request.

If you have something like:
response = InstalledAppsViewSet.as_view()(request, **kwargs),

to print the content of the response:
response.render().content – the error should be there.

👤Ioanna

Leave a comment