Danny
Danny

Reputation: 929

Django Rest filtering via query params

I am filtering by query params to find the user that matches the phone number in the query params.

Model:

from django.db import models
from django.contrib.auth.models import User
from phonenumber_field.modelfields import PhoneNumberField


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    profile_image = models.ImageField(upload_to='static/user_images', blank=True, null=True)
    phone_number = PhoneNumberField(unique=True)
    notifications = models.BooleanField(default=True)
    group_notifications = models.BooleanField(default=True)
    payment_info = models.CharField(max_length=100, default="PLACEHOLDER TEXT")

View:

class UsersList(generics.ListAPIView):
    serializer_class = UserSerializer

    def get_queryset(self):
         queryset = User.objects.all()
         phone_number = self.request.query_params.get('phone_number', None)
        if phone_number is not None:
             queryset = queryset.filter(userprofile_phone_number=phone_number)
        return queryset

Urls:

from django.conf.urls import include, url
from users import views

urlpatterns = [

     url(r'find$', views.UsersList.as_view()),

]

and this is the error I get when entering this: http://localhost:9000/find?phone_number=+447865940489

 FieldError at /api/v1/user/find
Cannot resolve keyword 'userprofile_phone_number' into field. Choices are: auth_token, date_joined, email, emailaddress, event, eventmembersattending, first_name, groupmember, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, request, socialaccount, suggestion, tags, user_permissions, username, userprofile

So what have I done wrong?

EDIT: Error solved but now I get an empty response

Upvotes: 3

Views: 3024

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47896

You need to use double underscores to access the phone_number field of the related userprofile field.

From Django docs on lookups that span relationships:

To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

Change the following line in get_queryset()

queryset = queryset.filter(userprofile_phone_number=phone_number) # wrong

to

queryset = queryset.filter(userprofile__phone_number=phone_number) # use double underscores

Upvotes: 2

Related Questions