Django 不会让我通过任何属性栏 'pk' 查询 table

Django won’t let me query a table by any attribute bar ‘pk’

所以我正在尝试通过关系属性“所有者”查询我的“个人资料”table,该属性链接到另一个 table“用户”。但是,当我尝试通过此属性进行查询时,出现以下错误: 'AssertionError: Expected view UserProfile to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.'

查询 table 我用过: Profile.objects.filter(owner__username = 用户名)

Models.py:

class User(models.Model):
    username = CharField(max_length = 80)

class Profile(models.Model):
    owner = models.OneToOneField('User', 
related_name = 'profile', on_delete = models.CASCADE)

Views.py:

class UserProfile(generics.GenericAPIView, 
mixins.RetrieveModelMixin):
    def get_queryset(self):
        username = self.kwargs['username']
        return Profile.objects.filter(owner__username=username)
    serializer_class = UserProfileSerializer
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

Urls.py:

urlpatterns = [
    path('user/<str:username>/profile/', views.UserProfile.as_view()),
]

为什么会出现此错误,我该如何解决?任何帮助将不胜感激。

谢谢,格雷。

将您认为的 lookup_fieldlookup_url_kwarg 属性设置为,

from rest_framework import generics


class UserProfile(generics.RetrieveAPIView):
    lookup_field = 'owner__username'
    lookup_url_kwarg = 'username'
    serializer_class = UserProfileSerializer
    queryset = Profile.objects.all()