This is some really simple code I am using with sqlalchemy and I am missing something basic here about how classes work.
class Game(Base):
__tablename__ = "games"
id = Column(Integer, primary_key=True)
a_name = Column(String)
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
print 'hi'
self.away_dictionary = {'name': self.a_name}
@hybrid_property
def stuff(self):
return self.away_dictionary
The following query works:
session.query(Game).first().a_name
but the following query returns an error:
session.query(Game).first().stuff
'Game' object has no attribute 'away_dictionary'
I also have an even more basic problem, when I query the Game class it doesn't print out 'hi'. So could someone please explain why 'hi' isn't printed out everytime I use a Game instance? And the second question is how can I build and access the away_dictionary I want to have for each instance of this class?
You're not creating a Game instance in your queries above, you only pass the Game class object. Hence the init() constructor is never called.
If you need a Game instance for query, you need this: session.query(Game()).first().stuff
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With