Reputation: 74
So I am populating the queryselectfield from my database.
def place_query():
return Place.query
class CreateItineraryForm(FlaskForm):
opts = QuerySelectField('Select a city',query_factory=place_query,allow_blank=True,get_label='city',validators=[DataRequired()])
days = IntegerField('Enter the number of days of stay',validators=[DataRequired()])
submit = SubmitField("Generate Itinerary")
But since my database has multiple tuples with the same city. So in my select field the same city shows up multiple times. Is there a way I can select only distinct city names?
This is the schema if that's helpful -
class Place(db.Model):
__tablename__ = 'places'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),nullable=False,index=True)
lat = db.Column(db.Float,nullable=False)
long = db.Column(db.Float,nullable=False)
city = db.Column(db.String(30),nullable=False,index=True)
user_reviews = db.relationship('Review',backref='subject',lazy=True)
def __init__(self,name,lat,long,city):
self.name = name
self.lat = lat
self.long = long
self.city = city
Thanks for the help!
Upvotes: 0
Views: 172
Reputation: 74
So the trick was to not use QuerySelectField
but to use SelectField
.
This is the new code -
# this returns a tuple of the form (city_name,)
cities = db.session.query(Place.city).group_by(Place.city).order_by(Place.city).all()
city_list = []
# here we create a list from the tuple
def create_list(cities):
for city in cities:
city_list.append(city[0])
return city_list
And the new select field looks like this -
opts = SelectField('Select a city',validators=[DataRequired()],choices=create_list(cities))
Upvotes: 1