数据库模型
class DoctorWaitTimes(db.Model):
__tablename__ = 'doctorwaittimes'
id = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.DateTime)
waittime = db.Column(db.Integer)
然后在ModelView类
中column_filters = ['datetime']
这允许用户选择
并显示可点击的日历,以便于输入日期/时间。这是完美的,但我想做两个改变。
我想删除以下选项:
但我无法在文档中找到任何内容。其次,我希望能够按星期几来过滤。例如,它只会在每个星期二显示。
column_filters = [
FilterTerminal(
DoctorWaitTimes.datetime, 'Day of Week',
options=(('1', 'Monday'), ('2', 'Tuesday'))
), 'datetime'
]
但是,我不确定如何让实际的过滤器工作。在MySQL中,您可以运行
SELECT * FROM doctorwaittimes WHERE AND DAYOFWEEK(datetime) = 1;
选择星期一,但我不知道如何使用DB Model。
答案 0 :(得分:1)
要从您的视图中删除多种类型的过滤器,请使用FilterConverter类。它有几个适用于每种类型列的过滤器列表。对其进行子类化并替换这些列表以删除不需要的过滤器。将新类指定为视图的filter_converter
属性:
from flask_admin.contrib.sqla import ModelView, filters
class DoctorFilterConverter(filters.FilterConverter):
datetime_filters = (
filters.DateTimeEqualFilter,
filters.DateTimeBetweenFilter
)
class DoctorView(ModelView):
filter_converter = DoctorFilterConverter()
column_filters = ['datetime']
您可以使用相同的方式添加新过滤器。可以通过以下方式实现星期几过滤:
class DayOfWeekFilter(filters.BaseSQLAFilter):
def __init__(self, column, name, options=None, data_type=None):
options = (
('1', filters.lazy_gettext(u'Monday')),
('2', filters.lazy_gettext(u'Tuesday')),
('3', filters.lazy_gettext(u'Wednesday')),
('4', filters.lazy_gettext(u'Thursday')),
('5', filters.lazy_gettext(u'Friday')),
('6', filters.lazy_gettext(u'Saturday')),
('7', filters.lazy_gettext(u'Sunday'))
)
super(DayOfWeekFilter, self).__init__(column, name, options, data_type)
def operation(self):
return filters.lazy_gettext('day of week')
def validate(self, value):
return value in ('1', '2', '3', '4', '5', '6', '7')
def apply(self, query, value, alias=None):
return query.filter(db.func.extract('dow', self.get_column(alias)) == value)
然后您可以将其添加到datetime_filters
:
class DoctorFilterConverter(filters.FilterConverter):
datetime_filters = (
filters.DateTimeEqualFilter,
filters.DateTimeBetweenFilter,
DayOfWeekFilter
)
请注意,没有通用的SQL函数来提取星期几。我使用了PostgreSQL EXTRACT函数。在MySQL中,您可以尝试使用WEEKDAY函数:
def apply(self, query, value, alias=None):
return query.filter(db.func.weekday(self.get_column(alias)) == value)
你需要更改选项的编号,因为WEEKDAY函数在星期一返回0,在星期日返回6。