简体   繁体   中英

Trying to pass a string for querying through Django Rest Framework urls

I have a django project and I am using Django Rest Frameowkr. I setup up a model, serializer, view, and url for a users model. I have the urls file. I want to passing in something like a username when the api url is called. I currently have it setup to have a primary key so when I enter a primary key it works. I want to switch it to username. I also want the serializer query to return the user object iwth the usename I pass in. I am using Djangos standard User object from django.contrib.auth.models Here is the code I have

Urls.py

from django.urls import path
from django.contrib.auth.models import User

from .views import UserListView, UserDetailsView
from .views import ProfileListView, ProfileDetailsView
from .views import RoleListView, RoleDetailsView

urlpatterns = [
    path('user/', UserListView.as_view()),
    path('user/<pk>', UserDetailsView.as_view()),
]

serializer.py file

from rest_framework import serializers

from django.contrib.auth.models import User
from users.models import Profile, Role

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'last_login')

Views.py file

from rest_framework.generics import ListAPIView, RetrieveAPIView

from django.contrib.auth.models import User

from users.models import Profile, Role
from .serializers import UserSerializer, ProfileSerializer, RoleSerializer

class UserListView(ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetailsView(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

Specify the lookup_field in UserDetailsView and change the urls pattern in urls.py as below

# urls.py
urlpatterns = [
    path('user/', UserListView.as_view()),
    path('user/', UserDetailsView.as_view()),
]


# views.py
class UserDetailsView(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM