简体   繁体   English

[Django rest 框架]:序列化一个字符串列表

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

I am working with django and djando rest framework我正在使用 django 和 djando rest 框架

I have created a new endpoint installedapps .我创建了一个新的端点installedapps When making GET requests to it, I want to return the data contained as a list of strings (list of installed apps)向它发出GET请求时,我想返回包含作为字符串列表(已安装应用程序列表)的数据

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:我试过@e4c5 代码,留下这样的:

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?有什么帮助吗?

You could use the serializers.ListField ,你可以使用serializers.ListField

ListField is a field class that validates a list of objects. ListField 是一个字段类,用于验证对象列表。

The ListField class also supports a declarative style that allows you to write reusable list field classes. ListField 类还支持声明式样式,允许您编写可重用的列表字段类。

You could write a custom field for serializer inheriting from ListField form the drf serializers which accepts list of strings.您可以为从ListField继承的序列化程序编写自定义字段,形成接受字符串列表的 drf 序列化程序。 Maybe like this, this example is already shown in the DRF docs.也许像这样,这个例子已经在 DRF 文档中显示了。

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.我们现在可以在整个应用程序中重用我们的自定义 StringListField 类,而不必为其提供子参数。

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

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但是您不想将 ListField 作为序列化程序,因为它不是一个

class InstalledAppsSerializer(serializers.Serializer):

    name = serializers.CharField(max_length=256)

    child = serializers.CharField()

    installed_apps_field = serializers.SerializerMethodField(
        'get_installed_apps')

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

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) , response = InstalledAppsViewSet.as_view()(request, **kwargs) ,

to print the content of the response:打印响应的内容:
response.render().content - the error should be there. response.render().content - 错误应该在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM