2015-10-15 89 views
1

我通過查詢參數進行篩選以查找與查詢參數中的電話號碼匹配的用戶。Django通過查詢參數進行休息篩選

型號:

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()), 

] 

,這是進入這個時候我得到的錯誤: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 

那麼我做錯了什麼?

編輯:錯誤解決,但現在我得到一個空的響應

回答

2

您需要使用雙下劃線訪問相關userprofile領域的phone_number領域。

從Django文檔上lookups that span relationships:

跨越的關係,只需要使用相關領域 跨模型,通過雙下劃線隔開的字段名,直到你得到你想要的 領域。

變化get_queryset()

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

以下行

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

感謝那些擺脫了錯誤的,但現在我得到一個空的迴應? – Danny

+0

也許是因爲在db中沒有具有'phone_number'值的用戶。檢查查詢集是否返回帶有該過濾器或'[]'的某個對象。 –

+0

嘗試使用數據庫中的電話號碼,仍然得到[] – Danny