Search code examples
pythondjangoapidjango-rest-frameworkdrf-queryset

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


So I’m trying to query my ‘Profile’ table by the relation attribute ‘owner’, which links to another table ‘User’. However, when I attempt to query by this attribute, I get the following error: '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.'

To query the table I used: Profile.objects.filter(owner__username = 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()),
]

Why am I getting this error, how would I fix it? Any help would be much appreciated.

Thanks, Grae.


Solution

  • set lookup_field and lookup_url_kwarg attributes in your view as,

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