1

I would like to make a query to a Django Model, but I do not know the fields to retrieve in advance. If I happen to know them and their number, I would do

MyModel.objects.values('field1', 'field2')

Indeed, I noticed that the values method takes optional positional arguments, *fields, as specified in the API reference.

Therefore, I thought of making a function, which takes *fields arguments and then using such args for my query. The wrapper would look like this:

def get_values(self, *fields):
   return MyModel.objects.values(fields)

However, I get an AttributeError: 'tuple' object has no attribute 'split' as the QuerySet API does not like my tuple. How could I work it out?

2 Answers 2

2

You need to unpack the values :)

def get_values(self, *fields):
    return MyModel.objects.values(*fields)  # note the *

Otherwise it would be like you wrote

def get_values(self, *fields):
    return MyModel.objects.values(('field1', 'field2'))  # note the extra ()

... hence the AttributeError: 'tuple' object has no attribute 'split' because tuples do not have the split method!

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

Comments

2

You can use the python unpacking feature: The * operator can be used to send a list of params as positional arguments:

>>> fields = ['field1', 'fields2']
>>> MyModel.objects.values(*fields)
<MyModelQueryset [{'field1': 'foo1', 'field2': 'bar2'}, {'field1': 'foo1', 'field2': 'bar2'}, {'field1': 'foo1', 'field2': 'bar2'}]>

Comments

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.