2015-06-06 73 views
0

我有一個GET請求,有時有pk參數,有時還沒有。 我想有一個處理它的視圖,但是我的編寫嘗試不成功。以下是我有:如何處理可選的GET參數?

@ajax 
@login_required 
def search_dist(request): 
    try: 
     pk = request.GET.get('pk') 
    except Exception: 
     dist_list = request.user.distributors.all() 
     starts_with = request.GET.get('query') 
     if starts_with: 
      dist_list = request.user.distributors.filter(
       surname__istartswith=starts_with) 
     return render(request, 'distributors/distributors_list.html', {'distributors': dist_list}) 
    else: 
     dist_list = request.user.distributors.filter(
      distributors_of_links=get_object_or_404(Link, pk=pk)) 
     starts_with = request.GET.get('query') 
     if starts_with: 
      dist_list = request.user.distributors.filter(distributors_of_links=get_object_or_404(
       Link, pk=pk)).filter(surname__istartswith=starts_with) 
     return render(request, 'distributors/distributors_list.html', {'distributors': dist_list}) 

我的模型的一部分:

class Distributor(models.Model): 


class Link(models.Model): 
    distributors = models.ManyToManyField(
     Distributor, blank=True, related_name='distributors_of_links') 


class UserProfile(AbstractUser): 
    distributors = models.ManyToManyField(
     Distributor, blank=True, related_name='distributors_of_user') 

與查詢:search_dist?query=V我:

GET /distributors/search_dist 404 NOT FOUND 
No Link matches the given query. 

我在做什麼錯?

+2

'pk = request.GET.get('pk')'不會引發異常。它給你沒有,而不是 – Pynchia

回答

2
pk = request.GET.get('pk') 

不會引發異常。如果pk不在GET中,它會給你None。 所以你的第一個案例從不執行。 試一下:

@ajax 
@login_required 
def search_dist(request): 
    pk = request.GET.get('pk', None) 
    if pk is None: 
     dist_list = request.user.distributors.all() 
     starts_with = request.GET.get('query') 
     if starts_with: 
      dist_list = request.user.distributors.filter(
       surname__istartswith=starts_with) 
     return render(request, 'distributors/distributors_list.html', {'distributors': dist_list}) 
    else: 
     dist_list = request.user.distributors.filter(
      distributors_of_links=get_object_or_404(Link, pk=pk)) 
     starts_with = request.GET.get('query') 
     if starts_with: 
      dist_list = request.user.distributors.filter(distributors_of_links=get_object_or_404(
       Link, pk=pk)).filter(surname__istartswith=starts_with) 
     return render(request, 'distributors/distributors_list.html', {'distributors': dist_list}) 
+0

這工作,謝謝。 'pk = request.GET.get('pk',None)''中的'',None'是什麼意思? – pythad

+1

'get()'帶一個可選的第二個參數,它是字典中不存在該鍵時返回的值。缺省值是'None',這裏你明確地返回'None'。 –

+0

@BurhanKhalid,謝謝! – pythad