i have a the following model:

class Tables(db.Model):  # fixme: rename the table name to table.
    __tablename__ = "tables"
    id = db.Column(db.Integer, primary_key=True)
    store_id = db.Column(db.Integer)
    name = db.Column(db.String(64))
    active = db.Column(db.Integer, default=0)
    orders = db.relationship("Order", backref='table', lazy='dynamic')

So far i have this.

tables = Tables.query.filter_by(store_id=1).all()  

free_tables = []
for table in tables:
    if len(table.orders.all()) == 0:
        free_tables.append(table.id)

what i want are the ids of the tables that have no orders bound to them. Is there a way to write this in a single line? thank you.

1 Answer 1

Try this:

from sqlalchemy import not_

tables = Tables.query.filter_by(store_id=1)\
           .filter(not_(Tables.orders.any())).all()