简体   繁体   English

Flask-Admin:使用Peewee的“选择字段”的自定义查询?

[英]Flask-Admin: Custom Query for Select Field with Peewee?

I have a model with a ForeignKeyField which gets rendered as a select field in the create/edit form in Flask-Admin. 我有一个带有ForeignKeyField的模型,该模型在Flask-Admin中的创建/编辑表单中作为选择字段呈现。 I would like to restrict the choices in the select field with a custom query so the user only has access to their own source addresses. 我想通过自定义查询来限制选择字段中的选择,以便用户只能访问自己的源地址。

All answers point I've found point in the direction of WTForms' QuerySelectField but that is only for SQLAlchemy and I am using Peewee. 我找到的所有答案都指向WTForms的QuerySelectField的方向,但这仅用于SQLAlchemy,并且我正在使用Peewee。

It seems like a pretty common thing to do though, so any other way? 这似乎是一件很普通的事情,所以还有其他办法吗?

class BulkMessage(BaseModel): title = CharField(null=True) source_address = ForeignKeyField( SourceAddress, related_name='bulk_messages', null=True )

It is pretty simple, actually: 实际上很简单:

Just override edit_form in the ModelView and create the field there with the query passed in choices , as seen in the docs : 只是覆盖edit_formModelView ,并在通过查询有创建字段choices ,如看到的文档

def edit_form(self):
    form = model_form(BulkMessage)

    form.source_address = SelectField(
        'Source Address',
        choices=[(sa.id, sa.title) for sa in SourceAddress.select().where(SourceAddress.owner == current_user.id)]
    )

    return form(obj=obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM