如何处理可选的GET参数?

时间:2015-06-06 18:23:55

标签: python django django-models django-views

我有一个GET请求,有时会有pk个参数,有时却没有。 我希望有一个处理它的视图,但我尝试编写它并不成功。这就是我所拥有的:

@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.

我做错了什么?

1 个答案:

答案 0 :(得分: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})