简体   繁体   中英

How to set an Array column with an empty array as default in SQLAlchemy + Postgres

I want to list the sources of a piece of information. Instead of creating another table with a one to many relation, I tought I'd use the Array type.

To I tried:

app = Flask(__name__)
db = SQLAlchemy(app)

...

class Edge(db.Model):

    sources = db.Column(
        db.ARRAY(db.String),
        default=db.ARRAY(db.String)
    )

But adding an edge gives me this error:

ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'ARRAY' [SQL: 'INSERT INTO edges (child_id, parent_id, sources) VALUES (%(child_id)s, %(parent_id)s, %(sources)s'] [parameters: {'child_id': 20, 'parent_id': 26, 'sources': ARRAY(String())}]

I can't find a good tutorial on how to use an array column with a default empty array.

Thanks

I eventually found the answer in the comments here :

sources = db.Column(
    db.ARRAY(db.String),
    server_default="{}"
)

A python callable can also be set as default value:

sources = db.Column(
    db.ARRAY(db.String),
    default=dict
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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