我正在使用rest_auth和rest_framework。
当我访问网址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数据,我需要做什么?我不希望它返回first_name
和last_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)),
答案 0 :(得分:0)
您可以在序列化程序中使用exclude
:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('first_name', 'last_name')
答案 1 :(得分:0)
文件路径
库/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', )