我已经实现了 DRF 并且不想强制电子邮件验证,但仍然使用它(在屏幕上提醒他们)。我只想返回 account_emailaddress.verified 和用户端点。实现这一目标的最佳方法是什么?我尝试从这篇文章中获取提示,但没有成功。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 = UserSerializerdef 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
2 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
如果我只想要不同序列化程序上的字段,我过去所做的方法是使用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。
添加回答
举报
0/150
提交
取消