user2950162
user2950162

Reputation: 1011

Building query string with form fields

I have a form which sends some parameters to a view where I use this parameters as a filter in a query. The search parameters are not obligatory and when a field of the form is left blank, I do not use it as a filter criteria.

I was trying to create the string for the query but get an error: "too many values to unpack"

Any Ideas of what could be happening? Also any ideas of a simpler way to do it would also be appreciated!

My view is like this (in the dict busca, the keys are form names and values database fields as django model)

def index(request):

a={}
busca={'marca':'brand = ', 'modelo':'model = ', 'tamano_min':'size >= '}
for i in request.POST:
    if i in ['marca', 'modelo', 'tamano_min']:
        valor=request.POST.get(i)
        a[i]=str.join(busca[i], valor)

query=list(a.values)
query=' and '.join(query)
latest_products = products.objects.filter(query, )

template = loader.get_template('search/index.html')
context = {'latest_products': latest_products}
return render(request, 'search/index.html', context)

Upvotes: 1

Views: 82

Answers (1)

alecxe
alecxe

Reputation: 473893

Don't reinvent the wheel by constructing your own query and use the power of Django ORM.

For example:

marca = request.POST.get('marca')
modelo = request.POST.get('modelo')
tamano_min = request.POST.get('tamano_min')

latest_products = products.objects.filter(brand=marca, model=modelo, size__gte=tamano_min)

get() helps to get the value of POST parameter or None if no parameter found in the dictionary.
__gte ending helps to add >= condition.

You may also want to check marca, modelo and tamano_min before using them:

latest_products = products.objects.all()
if marca is not None:
    latest_products = latest_products.filter(brand=marca)

And so on.

Upvotes: 2

Related Questions