Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy set default nullable=False

Tags:

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.

like image 901
John Bergson Avatar asked Apr 08 '15 18:04

John Bergson


People also ask

Are SQLAlchemy columns nullable by default?

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.

What is nullable false in SQLAlchemy?

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.

Is nullable true by default?

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.

What is Server default in SQLAlchemy?

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.


2 Answers

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.

like image 30
Maicon Mauricio Avatar answered Oct 23 '22 02:10

Maicon Mauricio


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) 
like image 72
Joran Beasley Avatar answered Oct 23 '22 03:10

Joran Beasley