1

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)

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

the issue is when one of those fields are left empty... if I have brand="" it will return the ones with no brand instead of all brands... also what the_gte after size means? thanks for the help!
I can check it before, but in case it is non existent, can I use something like brand=* to select all brands? otherwise I have the same problem because I have brand=marca and if marca is non existent I still have it in my query... and thanks again!
@user2950162 this is what if already does here. If you don't include brand= condition, you'll get all brands. See, you first make latest_products = products.objects.all(), then add filters on it.
so I would get all and then filter for each parameter like you did for marca?
@user2950162 yup, and since django querysets are "lazy" it wouldn't make an actual query to the database until iterated over or evaluated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.