I'm using SQLAlchemy for Flask to create some models. The problem is, nearly all my columns need nullable=False
, so I'm looking for a way to set this option as default when creating a column. Surely I could add them manually (as a Vim exercise), but I just don't feel like it today. For a reference, this is how my setup (models.py
) looks like:
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), nullable=False)
and many more. Is there a simple way of doing this?
Thanks in advance.
Columns are nullable by default The default value of SQLAlchemy nullable is False unless it's a primary key. A foreign key is also nullable by default.
nullable – If set to the default of True, indicates the column will be rendered as allowing NULL, else it's rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements.
1 Answer. Show activity on this post. So for check = Column(Boolean, default=False, nullable=True) default will be set to False when no value is specified i.e, nullable=True, right? Since nullable=True allows column to be NULL.
A client-side SQL expression, a server_default value, and server-side implicit defaults and triggers all have the server generate the default, which then must be fetched by the client if you want to be able to access it in the same SQLAlchemy session.
As Column
is a class, subclassing seems a lot more extensible to me 1. Depending on the IDE you are using, code completion may still work.
from sqlalchemy.sql.schema import Column as SAColumn class Column(SAColumn): def __init__(self, *args, **kwargs): kwargs.setdefault('nullable', False) super().__init__(*args, **kwargs)
db.Column
is the Column
class by SQLAlchemy. It was just imported by flask-sqlalchemy together with other SQLAlchemy definitions so the library users don't need to import from different places. Only one import is needed then. 1 One could set attributes directly after instantiation, like self.nullable
, for instance.
just create a wrapper that sets it
def NullColumn(*args,**kwargs): kwargs["nullable"] = kwargs.get("nullable",True) return db.Column(*args,**kwargs) ... username = NullColumn(db.String(80))
using functools.partial
as recommended in the comments
from functools import partial NullColumn = partial(Column,nullable=True)
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