Flask-SQLAlchemy - 在 QuerySelectField 中获取不同的元素?

Flask-SQLAlchemy - get distinct elements in QuerySelectField?

所以我正在从我的数据库中填充查询select字段。

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")

但是因为我的数据库有多个具有相同城市的元组。所以在我的 select 字段中,同一个城市出现了多次。有什么办法可以 select 只有不同的城市名称?

如果有帮助,这就是架构 -

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

感谢您的帮助!

所以诀窍是不使用 QuerySelectField 而是使用 SelectField.

这是新代码 -

# 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

新的 select 字段如下所示 -

opts = SelectField('Select a city',validators=[DataRequired()],choices=create_list(cities))