Definition of indices in SqlAlchemy with Alembic

I completely agree that this is a fairly simple question, and maybe he has an answer somewhere, but somehow I can not find it. (also I am not very good at SqlAlchemy)

I have this code -

from sqlalchemy import Column, Integer, Text, String, TIMESTAMP, Boolean, \ UnicodeText from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.schema import Sequence, ForeignKey, Index from zope.sqlalchemy import ZopeTransactionExtension import datetime DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class Users(Base): __tablename__ = "user_table" id = Column(Integer, Sequence('idseq'), primary_key = True) email = Column(String, unique=True) ip_addr = Column(String) created_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow) modified_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow) #Index('user_index',Users.c.email) 

How can I

  • Determine the index of a single column (say, by email) about this? (Probaby index = True will do this. And if so, then this is basically the next moment where I am lost)
  • How can I define a Multi Column Index (e.g. for email and ip_addr). I use alembic for migration and when I define something like: Index ('user_index', Users.c.email) [commented line] After defining the columns in the class, it gives me an error that "NameError: name" Users "is not defined ")

In alembic env.py, besides all the normal and standard lines, I have these two lines

 from tutorial.models import Base . . . target_metadata = Base.metadata 

My application name is a tutorial. And if this is necessary anyway, I use Pyramid as a frame. and postgres as db.

I say again that this can be a very simple question, but I just can't figure it out now, so any help would be great.

Thanks.

+6
source share
1 answer

For I, yes, use index=True in the field definition.

For II, just place the Index declaration outside the class definition:

 class Users(Base): __tablename__ = "user_table" id = Column(Integer, Sequence('idseq'), primary_key=True) email = Column(String, unique=True) ip_addr = Column(String) created_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow) modified_date = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow) Index('user_index', Users.c.email, Users.c.ip_addr) 
+6
source

All Articles