Mustafa Yılmaz
Mustafa Yılmaz

Reputation: 245

Filtering column values in flask-admin with one to many relationship

I am using flask-admin to create an admin interface. In my admin panel I have 2 tables first one is locations and the other one is demands which has a one to many relationship with location. I am trying to filter the location combobox on my demands form so users can only select active ones but I couldn't manage it. Is it possible? if yes how can I do it.

I tried to do it with form_ajax_refs but I failed.

class Location(db.Model):
    __tablename__ = 'Locations'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    active = db.Column(db.Boolean)

class Demand(db.Model):
    __tablename__ = 'Demands'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    delivery_from_id = db.Column(db.Integer, db.ForeignKey('Locations.id'))
    delivery_from = db.relationship(Location,
                                    backref=db.backref('demands_from', lazy='dynamic'),
                                    foreign_keys=[delivery_from_id],
                                    )

class DemandView(ModelView):
        form_ajax_refs = {
            'delivery_from': QueryAjaxModelLoader('delivery_from', db.session, Location, fields=['name', 'active'],
                                                  filters=["active=True"]),
        }

admin.add_view(ModelView(Location, db.session, 'Locations'))
admin.add_view(DemandView(Demand, db.session, 'Demands'))

Upvotes: 1

Views: 2098

Answers (1)

Mustafa Yılmaz
Mustafa Yılmaz

Reputation: 245

After a long search, finally I found the answer. Instead of using form_ajax_refs, I used query_factory to do the filtering.

    class DemandView(ModelView):
        form_args = {
            'delivery_from': {
                'query_factory': lambda: Location.query.filter_by(
                    active=True
                )
            }
        }

Upvotes: 8

Related Questions