views:

83

answers:

2

I want to check diferent values in the DB and create a new value, so i need to query and i don't know if i have to create a session in my SQLAlchemy class or how do i have to do it? using session like a global?, i didn't find in documentation.

Somethin like this:

class MyClass(Base):

    __tablename__ = 'my_class'
    __table_args__ = (UniqueConstraint('key', 'key2'),
                     {}
                     )
    id =  Column(Integer, Sequence('my_class_id'), primary_key=True)
    key = Column(String(30), nullable= False) #unique together key2
    key2 = Column(String(30), nullable = False) 
    value = Column(Integer, nullable=False)

    def __init__(self, key, key2):
        #check if exist key and key2
        values = session.query(MyClass.value).filter(MyClass.key == self.key).\
            filter(MyClass.key2 == self)

        if values:
            raise IntegrityError

        #get biggest value
        value = session.query(MyClass.value).filter(MyClass.key = self.key).order_by(asc(MyClass.value)) #I'm not shure if i need 'asc'
        #no value new key and key2

        if not value:
            self.key = key
            self.key2 = key2
            self.value = '000'
            return

        #i used a single table beacuse is easier to understand
        #in this example
        self.key = key
        self.key2 = key
        self.value = increment(value.first())

I'm using SQLALchemy 6.2 and declarative

Thanks

A: 

I found here that we can do Session.object_session(self):

def new_value(self):
    #not really DRY
    #the object has to be binded with some session first.
    session = Session.object_session(self) # << this is the important stuff

    #check if exist key and key2
    values = session.query(MyClass.value).filter(MyClass.key == self.key).\
        filter(MyClass.key2 == self)

    if values:
        return #None

    #get biggest value
    value = session.query(MyClass.value).\
               filter(MyClass.key = self.key).\
               order_by(desc(MyClass.value))

    return increment(value.first())
sacabuche
This will not work for newly-created objects that haven't been added to a session, though. And since you're trying to use it from a constructor, this would mean you cannot create new objects at all.
Marius Gedminas
in fact i changed this part of code inside of a MapperExtension, inside of before_insert, i'll update my code
sacabuche
+1  A: 

You will have to do your own session management -- e.g. define a module-global session object.

For example, Pylons applications define their session like this:

from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker())

and then later bind it to an engine with

Session.configure(bind=engine)

Using scoped_session will mean that your code is thread-safe (each thread will use its own session).

Marius Gedminas