Django Rest通过查询参数进行过滤

时间:2015-10-15 16:12:25

标签: python django rest filtering django-rest-framework

我正在通过查询参数进行过滤,以找到与查询参数中的电话号码匹配的用户。

型号:

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")

查看:

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

的url:

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

urlpatterns = [

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

]

这是我输入时遇到的错误:ClassUtils.isAssignable

 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

那我做错了什么?

编辑:错误已解决,但现在我得到一个空响应

1 个答案:

答案 0 :(得分:2)

您需要使用双下划线才能访问相关phone_number字段的userprofile字段。

来自lookups that span relationships:

上的Django文档
  

要跨越关系,只需使用相关字段的字段名称即可   跨越模型,用双下划线分隔,直到你到达   你想要的领域。

更改get_queryset()

中的以下行
queryset = queryset.filter(userprofile_phone_number=phone_number) # wrong

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