2

I am starting to use Django and I have this code in my app:

filtro = "marca:samsung_modelo:s3"
mifiltro = filtro.split('_')
cadena = '0'

for caracteristica in mifiltro:
    if not cadena == '0':
        cadena += ", "
    elif cadena == '0':
        cadena = ''

    aux = caracteristica.split(':')
    cadena += aux[0] + "='" + aux[1] + "'"

Then cadena is:

marca='samsung',modelo='s3'

I want use this variable as filter like this:

productos = Producto.objects.filter(cadena)

But I get the error "too many values to unpack".

If I write in my code:

productos = Producto.objects.filter(marca='samsung',modelo='s3')

It works fine. Can I use a string to filter an object?

Ry-
  • 218,210
  • 55
  • 464
  • 476
jakama
  • 43
  • 1
  • 7
  • A better way I found is here https://stackoverflow.com/questions/852414/how-to-dynamically-compose-an-or-query-filter-in-django – ERIC NDERITU Mar 29 '21 at 11:22

2 Answers2

2

You can use a dict , then unpack all values of the dict as parameters using **:

_vals = {'marca': 'samsung', 'modelo': 's3'}
productos= Producto.objects.filter(**_vals)
Mp0int
  • 18,172
  • 15
  • 83
  • 114
2

My code finally works! I needed to use Q objects, so I modified the code like this:

filtro = "marca:1|2"
aux = filtro.split(':')
mismarcas = aux[1].split('|')
mimarca = []

for marca in mismarcas:
    mimarca += [Q(**{ aux[0]: marca})]

productos = Producto.objects.filter(reduce(operator.or_, mimarca))
Ry-
  • 218,210
  • 55
  • 464
  • 476
jakama
  • 43
  • 1
  • 7
  • This solution helped me, too, but I don't understand why. I needed to use `Q` obj., too, because sometimes my filter argument would be several terms `reduce`d with `and_`. However, when my filter was a single term referring to a specific model object, I'd get the "unpack" error. I changed my code from `Q('item__topic', topic)` to `Q(**{'item__topic': topic})`, now it works. ‍♀️ – Mr. Lance E Sloan Apr 28 '21 at 02:34