我已经实现了DRF,并且不想强制进行电子邮件验证,但仍然可以使用它(在屏幕上提醒他们)。我只想返回account_emailaddress.verified以及用户端点。实现此目标的最佳方法是什么?我尝试从此post中获取提示,但没有成功。
account_emailaddress来自我已实现的django-allauth应用 https://github.com/pennersr/django-allauth/blob/master/allauth/account/models.py
序列化器:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.CustomUser
fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'avatar')
查看:
class UserView(generics.RetrieveUpdateDestroyAPIView):
queryset = CustomUser.objects.all()
serializer_class = UserSerializer
def get(self, request, *args, **kwargs):
try:
user = self.queryset.get(pk=kwargs["user"])
return Response(UserSerializer(user).data)
except CustomUser.DoesNotExist:
return Response(
data={
"message": "User with id: {} does not exist".format(kwargs["user"])
},
status=status.HTTP_404_NOT_FOUND
)
def put(self, request, *args, **kwargs):
try:
user = self.queryset.get(pk=kwargs["user"])
serializer = UserSerializer()
user = serializer.update(user, request.data)
return Response(UserSerializer(user).data)
except CustomUser.DoesNotExist:
return Response(
data={
"message": "User with id: {} does not exist".format(kwargs["user"])
},
status=status.HTTP_404_NOT_FOUND
)
编辑:感谢schillingt的回答,我能够修改序列化程序以根据需要工作
from allauth.account.models import EmailAddress
class UserSerializer(serializers.ModelSerializer):
verified_email = serializers.SerializerMethodField()
class Meta:
model = models.CustomUser
fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'avatar', 'verified_email')
def get_verified_email(self, obj):
try:
email_address = EmailAddress.objects.get(user_id=obj.id)
return email_address.verified
except EmailAddress.DoesNotExist:
return None
答案 0 :(得分:2)
如果我只想在其他序列化程序上使用该字段,我过去所做的方式就是使用SerializerMethod
类。我猜上了account_emailaddress
的课程。
class UserSerializer(serializers.ModelSerializer):
verified_email = serializers.SerializerMethod()
class Meta:
model = models.CustomUser
fields = (..., 'verified_email')
def _verified_email(self, obj):
try:
return obj.account_emailaddress.verified
except EmailAddress.DoesNotExist:
return None
然后在视图集上,应在account_emailaddress
属性的select_related
中将queryset
包括在内,以免对每个CustomUser
进行附加查询。>
答案 1 :(得分:0)
您可以在序列化器字段上使用源映射,以包括相关模型中的字段,例如(假设已验证是布尔字段);
class UserSerializer(serializers.ModelSerializer):
verified = serializers.BooleanField(source='account_emailaddress.verified', read_only=True)
class Meta:
model = models.CustomUser
fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'avatar', 'verified ')
请注意,这也假设account_emailaddress是CustomUser模型上的一个字段,或者可以通过OneToOne字段像 custom_user.account_emailaddress 一样进行访问。