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()')
asked Feb 8, 2022 at 21:47
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-1200032.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)
... 
>>> 
answered Feb 9, 2022 at 5:25
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.