You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.6 KiB

from django.contrib.auth.models import User
from rest_framework import serializers
class UserDescSerializer(serializers.ModelSerializer):
"""文章列表中引用的嵌套序列化器"""
class Meta:
model = User
fields = [
'id',
'username',
# 'last_login',
# 'date_joined'
]
class UserRegisterSerializer(serializers.ModelSerializer):
# lookup_field字段将作为url中的地址
url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='username')
class Meta:
model = User
fields = [
'url',
'id',
'username',
'password',
2 years ago
'is_superuser', # 是否是管理员
]
extra_kwargs = {
2 years ago
'password': {'write_only': True},
'is_superuser': {'read_only': True},
}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
def update(self, instance, validated_data):
if 'password' in validated_data:
password = validated_data.pop('password') # 对密码加密后再存入数据库
instance.set_password(password)
return super().update(instance, validated_data)
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'id',
'username',
'last_name',
'first_name',
'email',
'last_login',
'date_joined',
]