Joost Döbken
Joost Döbken

Reputation: 4017

return NOT NULL columns from class with sqlalchemy

In python sqlalchemy I would like to get the nullable=False columns of my class, including JSONB types.

Here's my example class:

class MyClass():
    __tablename__ = 'myclass'
    id = Column("id", primary_key=True)
    name = Column(String, nullable=False)
    body = Column(JSONB, nullable=False)
    irrelevant = Column(String, nullable=True)

Using the module inspect I can get the members of MyClass and apply a filter:

# list of possible attributes
attr = [a for a in inspect.getmembers(MyClass,lambda :not(inspect.isroutine(a))) if not '__' in  a[0]]

But it is not possible to check if nullable=False is in a column. Eventually I want to get the columns: name and body.

Upvotes: 3

Views: 1584

Answers (1)

r-m-n
r-m-n

Reputation: 15090

You can iterate over MyClass.__table__.columns and get names of not nullable columns

column_names = [col.name for col in MyClass.__table__.columns if not col.nullable]

Then get attributes with getattr

attrs = [getattr(MyClass, column_name) for column_name in column_names]

Upvotes: 3

Related Questions