在 Django 中通过用户名查找配置文件
Lookup to Profile via username in Django
我目前有以下设置,它允许我在配置文件 table 中提取给定 pk 的配置文件详细信息。您会看到我已经从序列化程序中的用户模型中提取了用户名,以显示在视图中。我正在尝试修改代码以提取给定用户名的配置文件,但将 'pk' 更改为 'username' 并使用查找字段不起作用。
我认为这是因为我正在尝试倒退。因此,我是否应该创建一个接受用户名的 UserSerializer,然后通过 'user' 字段将其 link 发送到 ProfileSerializer(这是用户模型 pk 的一对一 link )?我不知道该怎么做。
urls.py
urlpatterns = [
path(r'api/profile/<pk>/', views.ProfileView.as_view()),
]
serializers.py
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
class Meta:
model = Profile
fields = ('user', 'gender', 'dob', 'username')
lookup_field = 'username'
views.py
class ProfileView(RetrieveAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
您只需向 ProfileView
class 添加两个属性。
class ProfileView(RetrieveAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'user__username'
lookup_url_kwarg = 'username'
这将表明您将根据 username
过滤您的查询集。现在有了像
这样的路径
path('some-path/<slug:username>/', ProfileView.as_view())
您可以根据用户名过滤 Profile
查询集。
我目前有以下设置,它允许我在配置文件 table 中提取给定 pk 的配置文件详细信息。您会看到我已经从序列化程序中的用户模型中提取了用户名,以显示在视图中。我正在尝试修改代码以提取给定用户名的配置文件,但将 'pk' 更改为 'username' 并使用查找字段不起作用。
我认为这是因为我正在尝试倒退。因此,我是否应该创建一个接受用户名的 UserSerializer,然后通过 'user' 字段将其 link 发送到 ProfileSerializer(这是用户模型 pk 的一对一 link )?我不知道该怎么做。
urls.py
urlpatterns = [
path(r'api/profile/<pk>/', views.ProfileView.as_view()),
]
serializers.py
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
class Meta:
model = Profile
fields = ('user', 'gender', 'dob', 'username')
lookup_field = 'username'
views.py
class ProfileView(RetrieveAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
您只需向 ProfileView
class 添加两个属性。
class ProfileView(RetrieveAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
lookup_field = 'user__username'
lookup_url_kwarg = 'username'
这将表明您将根据 username
过滤您的查询集。现在有了像
path('some-path/<slug:username>/', ProfileView.as_view())
您可以根据用户名过滤 Profile
查询集。