Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )

???

like image 721
GregL83 Avatar asked Jun 23 '11 14:06

GregL83


People also ask

Does * args return a list?

*args returns a list containing only those arguments that are even.

What is admin py in Django?

The admin.py file is used to display your models in the Django admin panel. You can also customize your admin panel.


1 Answers

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.

like image 109
Gabi Purcaru Avatar answered Sep 21 '22 17:09

Gabi Purcaru