Flask SQLAlchemy querying a column with "not equals"

PythonSqlalchemyFlaskFlask Sqlalchemy

Python Problem Overview


I can query my Seat table for all seats where there is no invite assigned:

seats = Seat.query.filter_by(invite=None).all()

However, when querying for all seats that have an invite assigned, I get a NameError:

seats = Seat.query.filter_by(invite!=None).all()

NameError: name 'invite' is not defined

Here is my Seat class:

class Seat(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    invite_id = db.Column(db.Integer, db.ForeignKey('invite.id'))
    invite = db.relationship('Invite',
        backref=db.backref('folks', lazy='dynamic'))

How can I query for all seats where the owner is not blank?

Python Solutions


Solution 1 - Python

The filter_by() method takes a sequence of keyword arguments, so you always have to use = with it.

You want to use the filter() method which allows for !=:

seats = Seat.query.filter(Seat.invite != None).all()

Solution 2 - Python

I think this can help http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.isnot

Is None

query.filter(User.name == None)

or alternatively, if pep8/linters are a concern

query.filter(User.name.is_(None))

Is not None

query.filter(User.name != None)

or alternatively, if pep8/linters are a concern

query.filter(User.name.isnot(None))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanPlusPlusView Question on Stackoverflow
Solution 1 - PythonNathan VillaescusaView Answer on Stackoverflow
Solution 2 - Pythonbull90View Answer on Stackoverflow