PythonicRitual
PythonicRitual

Reputation: 9

Lookup to Profile via username in Django

I currently have the setup below, which allows me to extract the profile details for a given pk in the Profile table. You will see that I have extracted the username from the User model in the serializer, to display in the view. I am trying to modify the code to extract the profile for a given username, but changing 'pk' to 'username' and using a lookup field doesn't work.

I think this is because I'm trying to do it backwards. Should I therefore create a UserSerializer that accepts the username and then link it to the ProfileSerializer via the 'user' field (this is the one-to-one link to the pk of the User model)? I am not sure how to do that.

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

Upvotes: 0

Views: 345

Answers (1)

Roham
Roham

Reputation: 2110

You just have to add two attributes to your ProfileView class.

class ProfileView(RetrieveAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'user__username'
    lookup_url_kwarg = 'username'

which will tell that you're going to filter your queryset based on username. Now with having a path like

path('some-path/<slug:username>/', ProfileView.as_view())

you can filter your Profile queryset based on a username.

Upvotes: 2

Related Questions