OrganicPanda OrganicPanda - 3 years ago 187
Python Question

python data attributes in sqlalchemy model

I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening:

# -*- coding: utf-8 -*-
import cherrypy
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql://USER:PASS@localhost/SCHEMA?charset=utf8', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()

class User(Base):
__tablename__ = 'user'

id = Column(Integer, primary_key=True)
username = Column(String, nullable=False)
name = Column(String, nullable=False)
email = Column(String, nullable=False)

def __init__(self, username, name, email):
self.username = username = name = email
self.data_attribute = "my data attribute"
print "__init__"

def __repr__(self):
print "__repr__"
return "<User('%s','%s', '%s')>" % (self.username,,

class Root(object):

def test(self):
our_user = session.query(User).one()
return our_user.data_attribute #error

if __name__ == '__main__':


That code errors because when the objects are taken from the DB
doesn't run so
doesn't exist. If I put
in with the
objects is becomes a class attribute (I think) and therefore carries the same value for all instances of
. This is not what I want.

What do I need to do to have a data attribute on my User object that doesn't come from the DB but also is unique for each instance of

Edit: I should probably point out that
will not always just be a simple string set in
- this is just to demonstrate the problem.

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download