TheOrganist24
TheOrganist24

Reputation: 89

How to order dropdown list in QuerySelectField

I have a python wtforms QuerySelectField which pulls data from an unordered database. How do I make the list appear in alphabetical order?

Upvotes: 0

Views: 403

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52937

Apply an ordering to the query used by the field. Given a model such as

class Car(Base):
    ...
    make = Column(Unicode, nullable=False)
    model = Column(Unicode, nullable=False)

you'd pass a query or a query factory that produces ordered results:

def cars():
    return session.query(Car).order_by(Car.make, Car.model)

class Cars(Form):
    car = QuerySelectField(query_factory=cars)

Alternatively you could set the query dynamically in a view, if not using factories:

form.car.query = session.query(Car).order_by(Car.make, Car.model)

If your models lack a descriptive string representation, you can customize the label used when rendering the options, so that the order is more apparent:

def get_car_label(car):
    return f"{car.make} {car.model}"

class Cars(Form):
    car = QuerySelectField(query_factory=cars, get_label=get_car_label)

Upvotes: 2

Related Questions