我有一個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.
我在做什麼錯?
'pk = request.GET.get('pk')'不會引發異常。它給你沒有,而不是 – Pynchia