Home > database >  How to create an array or list column in SQLAlchemy model?
How to create an array or list column in SQLAlchemy model?

Time:02-10

I know it's possible to create array of string in postgres but I want to create a model in sqlalchemy that contains a list or array column but I don't know how

Please view the code below

class Question(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column([String],nullable=False)
    answer = Column(String,nullable=False)
    created_at = Column(TIMESTAMP(timezone=true),server_default=text('now()')




CodePudding user response:

You need to use:

from sqlalchemy.dialects.postgresql import ARRAY

Here:

from datetime import datetime
from sqlalchemy import *
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Question1(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column(ARRAY(String),nullable=False)
    answer = Column(String,nullable=False)

Example:

Python 3.8.2 (default, Dec 21 2020, 15:06:04) 
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> from sqlalchemy import *
>>> from sqlalchemy.dialects.postgresql import ARRAY
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> class Question1(Base):
...     __tablename__= 'questions'
...     id = Column(Integer, nullable=False, primary_key=True)
...     question = Column(String,nullable=False)
...     options = Column(ARRAY(String),nullable=False)
...     answer = Column(String,nullable=False)
... 
>>> 

  • Related