简体   繁体   English

SQLAlchemy 设置默认 nullable=False

[英]SQLAlchemy set default nullable=False

I'm using SQLAlchemy for Flask to create some models.我正在使用 SQLAlchemy 为 Flask 创建一些模型。 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.问题是,几乎我所有的列都需要nullable=False ,所以我正在寻找一种在创建列时将此选项设置为默认值的方法。 Surely I could add them manually (as a Vim exercise), but I just don't feel like it today.当然我可以手动添加它们(作为 Vim 练习),但我今天不喜欢它。 For a reference, this is how my setup ( models.py ) looks like:作为参考,这是我的设置 ( models.py ) 的样子:

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.提前致谢。

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按照评论中的建议使用functools.partial

from functools import partial
NullColumn = partial(Column,nullable=True)

As Column is a class, subclassing seems a lot more extensible.由于Column是 class,子类化似乎更具可扩展性。

from sqlalchemy.sql.schema import Column as Col
    
class Column(Col):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('nullable', False)
        super().__init__(*args, **kwargs)

The accepted answer creates a wrapper for a nullable = True column called NullColumn , which is already what Column does by default.接受的答案为名为NullColumnnullable = True列创建了一个包装器,这已经是Column默认情况下所做的。 The question asks to set nullable = False (not True ) as the default when creating a column.该问题要求在创建列时将nullable = False (不是True )设置为默认值。

from sqlalchemy import Column as Col

def Column(*args, **kwargs):
    kwargs.setdefault('nullable', False)
    return Col(*args, **kwargs)

This function returns a Column with nullable = False by default, which can also be overwritten with nullable = True if needed (unlike the functools.partial solution).这个 function 默认返回一个nullable = FalseColumn ,如果需要也可以用nullable = True覆盖(与functools.partial解决方案不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM