Home > Back-end >  How to assign bulk parameter to Django object values list?
How to assign bulk parameter to Django object values list?

Time:04-02

How to assign bulk parameters to the Django object values list?

  1. Bulk parameter assignment

    strlist = ["a","b","c"]

    model1. objects.filter(**kwargs).values_list(strlist)

    Result: TypeError: unhashable type: 'list'

  2. Manual assignment

    model1. objects.filter(**kwargs).values_list("a","b","c")

    Result is ok

How to assign a bulk parameter assignment?

CodePudding user response:

Short Answer:
Try:

model1. objects.filter(**kwargs).values_list(*strlist)

Explaination:
The problem is that the function requires you to enter unpacked values. There is a difference between a list and *list. *list represents the unpacking of individual values inside a list and then entering them.
So,

model1. objects.filter(**kwargs).values_list(strlist)

Is interpreted as

model1. objects.filter(**kwargs).values_list(["a", "b", "c"])

But

model1. objects.filter(**kwargs).values_list(*strlist)

Is interpreted as

model1. objects.filter(**kwargs).values_list("a", "b", "c")

Example 1:

a = [1,2,3,4]
print(a)
print(*a)

Output:

[1, 2, 3, 4]
1 2 3 4

So, while a represents the list a but in list form, *a represents the list a as its individual elements. Hence even if you try to index *a, it shows an error.
On the other hand **dict1 refers to the scenario where the dictionary dict1 has the arguments as key-value pairs. Eg.:

def b(hel, lo, wo, rl):
    print(hel, lo, wo, rl)

a = [1,2,3,4]
d = {'hel':1, 'lo':2, 'rl':3, 'wo':4}
b(*a)
b(**d)

Output:

1 2 3 4
1 2 4 3
  • Related