我有一个django项目,正在使用Django Rest Frameowkr。我为用户模型设置了模型,序列化器,视图和URL。我有网址文件。我想在调用api URL时传递类似用户名的名称。我目前已将其设置为具有主键,因此当我输入主键时它可以工作。我想将其切换为用户名。我还希望序列化程序查询返回我传递的使用名的用户对象。
我正在使用User
中的Djangos标准django.contrib.auth.models
对象
这是我的代码
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文件
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文件
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
答案 0 :(得分:1)
在lookup_field
中指定 UserDetailsView
,并在urls.py
中更改网址格式,如下所示
# urls.py
urlpatterns = [
path('user/', UserListView.as_view()),
path('user/<username>', UserDetailsView.as_view()),
]
# views.py
class UserDetailsView(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'username'