簡體   English   中英

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

[英]Flask-SQLAlchemy - get distinct elements in QuerySelectField?

所以我正在從我的數據庫中填充查詢選擇字段。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM