Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 721
ted Avatar asked Oct 22 '18 08:10

ted


2 Answers

I eventually found the answer in the comments here:

sources = db.Column(
    db.ARRAY(db.String),
    server_default="{}"
)
like image 194
ted Avatar answered Nov 05 '22 00:11

ted


A python callable can also be set as default value:

sources = db.Column(
    db.ARRAY(db.String),
    default=dict
)
like image 39
hjpotter92 Avatar answered Nov 04 '22 23:11

hjpotter92