Fred Wu
Fred Wu

Reputation: 928

Pass in parameters in django query

Here is my case:

I have different types of users to share one general view, but I want return different fields for them. I used values() to specific fields, like this values('f1', 'f2'), and it returned the queryset.

Then, I wanted to use a variable to store the fields to query, and pass it in the values(), but failed. My snippets look like this:

list = ('f1', 'f2')
e = Entity.objects.all().values(list)

I tried tuple, list, str, but all failed.

Error msg:

object has no attribute 'split'

What is the correct way to get this function?

Upvotes: 2

Views: 128

Answers (1)

alecxe
alecxe

Reputation: 473893

You need to unpack the list:

fields = ('f1', 'f2')
e = Entity.objects.all().values(*fields)

Also, do not name a variable as list - it shadows built-in varaible type:

>>> a = list()
>>> a
[]
>>> list = ('f1', 'f2')
>>> a = list()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Hope that helps.

Upvotes: 2

Related Questions