6

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()')




1
  • Did you think of using 1 to many? Commented Feb 8, 2022 at 21:56

1 Answer 1

5

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)
... 
>>> 

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.