正确的方法来定义RetrieveAPIView视图类

时间:2016-10-19 14:00:43

标签: python django django-rest-framework

阅读django-rest-framework的文档后,这就是我所做的: serializers.py:

class UserRegistrationDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            User._meta.pk.name,
        )

views.py

class RegistrationDetailView(generics.RetrieveAPIView):
    serializer_class = serializers.UserRegistrationDetailSerializer
    permission_classes = (
        permissions.AllowAny,
    )
    lookup_field='email'

    def get_queryset(self):
        email = self.kwargs.get('email')
        user = get_object_or_404(User, email = email)
        if user:
            if settings.get('SEND_ACTIVATION_EMAIL'):
                self.send_activation_email(user)
            elif settings.get('SEND_CONFIRMATION_EMAIL'):
                self.send_confirmation_email(user)

        return User.objects.all()

urls.py:

urlpatterns = [
    url(r'^register/(?P<email>\w+|[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', views.RegistrationDetailView.as_view(), name='register_detail'),
]

我已定义def get_queryset(self):而非仅提供queryset变量,因为如果用户存在于数据库中,我想向用户发送电子邮件。它按照要求工作,但由于我是django-rest-framework的新手,我不太确定这是否是正确的方法。我在这里做了什么不必要的事吗?

0 个答案:

没有答案