D
D
Dmitry Vyatkin2015-10-26 22:17:06
Django
Dmitry Vyatkin, 2015-10-26 22:17:06

How to make a request to the database depending on the GET parameters?

Good evening!
There is a function in views.py:

def shows(request):
  form = SelectParams(request.GET)
   if not form.is_valid():
    return HttpResponseBadRequest('You have entered the wrong data.')
  country    = form.cleaned_data['country']
  state        = form.cleaned_data['state']
  city          = form.cleaned_data['city']
  data         = Model.objects.filter(country=country, city=city, state=state) # TODO
  return render(request, 'template/index.html', {
    'data'    : data,
    'form'   : form,
    })

Tell me how to make a request to the model correctly, depending on what the user has chosen without using the if heap? The user can select country only, state only, city only, country and state, or country state and city. Tried the Q object but there is some confusion going on.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2015-10-27
@dim137

With an explicit indication of the city, it makes no sense to filter by country and state; with an explicit indication of the state, there is no point in filtering by country. The code may look something like this (I, of course, have no way to check):

location = form.cleaned_data
city, state, country = location['city'], location['state'], location['country']
kwargs = ({'city': city} if city
   else ({'state': state} if state
   else {'country': country} if country))
data = Model.objects.filter(**kwargs)

All this does not negate the need to filter the list of cities on the client when choosing a country / state.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question