سؤال

I am following the quick Quick Start Tutorial(http://www.django-rest-framework.org/tutorial/quickstart#quickstart) Its possible to create/delete/update a user in database if we know its "id", But is it possible to do the same for a user with particular email ? Please also suggest the modifications needed to make this possible and enable API to lookup by email like users/email.

هل كانت مفيدة؟

المحلول

Set the lookup_field and lookup_url_kwarg on your view or viewset that subclasses GenericAPIView. A basic example using a ModelViewSet and a SimpleRouter would look like this:

views.py:

class UserViewSet(viewsets.ModelViewSet):
    lookup_field = 'email'
    lookup_url_kwarg = 'email'

urls.py:

router = routers.SimpleRouter()
router.register(r'^users', UserViewSet)
urlpatterns = router.urls

نصائح أخرى

If you are using HyperlinkedModelSerializer, you must set lookup_field in the serializer too.

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'username')
        lookup_field = 'email'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top