[Fixed]-Django make variable visible

1👍

Another way to this is to create filter dictionary

filter_kw = {}
if query !=something:
    filter_kw['user_name'] = request.user
elif query2 != something:
    filter_kw['amount'] = 20
all_toys = Toys.objects.filter(**filter_kw)

0👍

Why can’t you declare the value on top and use it in all conditions?

all_toys = Toys.objects.all()

if query != something:
    all_toys = all_toys.filter(...)
else:
    all_toys = all_toys.filter(...)

In your case, all_toys will not have been defined in the elif block

Leave a comment