GregL83
GregL83

Reputation: 615

Python/Django - *args as list

I'm using the .order_by() method/function; however, I want to construct the order_by fields dynamically. The problem is .order_by() expects to receive a string or buffer. So, I can't build a list or tuple or object to send to the function. How can I achieve this goal?

I wanted to do something like:

field_list = []
for field in fields:
  field_list.append( field )
model.objects.all().order_by( field_list )

???

Upvotes: 5

Views: 890

Answers (1)

Gabi Purcaru
Gabi Purcaru

Reputation: 31524

You can use model.objects.all().order_by(*field_list); this is due to the fact that order_by accepts multiple string arguments, not lists of multiple strings.

See This chapter in djangobook, search for order_by, and this for arguments unpacking.

Upvotes: 8

Related Questions