Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
Joost Döbken Avatar asked Jul 22 '26 23:07

Joost Döbken


1 Answers

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]
like image 162
r-m-n Avatar answered Jul 25 '26 13:07

r-m-n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!