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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With