如何自定义 rest-auth/user 返回的 JSON 数据

How to customize the JSON data returned by rest-auth/user

我正在使用 rest_auth 和 rest_framework。

当我访问 URL http://localhost:8080/rest-auth/user/ GET 我得到以下 JSON 数据

{
    "username": "latest",
    "email": "latest@gmail.com",
    "first_name": "some first name",
    "last_name": "some last name"
}

问题

我需要做什么才能自定义 JSON 数据 returned?我不想 return first_namelast_name?

尝试过

我尝试创建名为 serializers.py 的文件并向其中添加了以下内容,但它没有任何效果。

from rest_framework import serializers
from .models import *
import re

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email')

我的 urls.py 包含以下内容

url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'),
url(r'^signup/$', TemplateView.as_view(template_name="signup.html"),
    name='signup'),
url(r'^email-verification/$',
    TemplateView.as_view(template_name="email_verification.html"),
    name='email-verification'),
url(r'^login/$', TemplateView.as_view(template_name="login.html"),
    name='login'),
url(r'^password-reset/$',
    TemplateView.as_view(template_name="password_reset.html"),
    name='password-reset'),
url(r'^password-reset/confirm/$',
    TemplateView.as_view(template_name="password_reset_confirm.html"),
    name='password-reset-confirm'),
#
url(r'^user-details/$',
    TemplateView.as_view(template_name="user_details.html"),
    name='user-details'),
url(r'^password-change/$',
    TemplateView.as_view(template_name="password_change.html"),
    name='password-change'),


# this url is used to generate email content
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    TemplateView.as_view(template_name="password_reset_confirm.html"),
    name='password_reset_confirm'),

url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
url(r'^account/', include('allauth.urls')),
url(r'^admin/', include(admin.site.urls)),

您可以在序列化程序中使用 exclude

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ('first_name', 'last_name')

文件路径

Lib/site-packages/rest_auth/serializers.py

class UserDetailsSerializer(serializers.ModelSerializer):
"""
User model w/o password
"""
class Meta:
    model = UserModel
    fields = ('username', 'email')
    read_only_fields = ('email', )