I'm rather new to both Python and SQLAlchemy. I have been trying to create
a class with a function to populate the name field based on values in
related tables. A good example would be Diablo 2 item generation. Please
note the following code is not really meant to work, it is just a very
basic example what I am trying to accomplish.
class Prefix(Base):
pk = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(20))
class Suffix(Base):
pk = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(20))
class Item(Base):
pk = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(20))
class MagicItem(Base)
# has 1 prefix, 1 suffix, 1 Item
pk = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String(20))
prefix_fk = Column(ForeignKey('prefix.pk'))
suffix_fk = Column(ForeignKey('suffix.pk'))
item_fk = Column(ForeignKey('item.pk'))
prefix = relationship("Prefix")
suffix = relationship("Suffix")
item = relationship("Item")
@classmethod
set_name(cls):
# set to prefix.name + " " + item.name + " " + suffix.name
return
Is an @classmethod the right way to do this?
I can't seem to just use cls.<column name> to reference the actual object
values. For example, if I were the following side the set_name() function
call:
print(cls.prefix_fk)
> MagicItem.prefix_fk
I do not get 1, like I would expect. It is printing the table.column name,
but not the value of that column for the object that called the function.
I was able to work around this by querying like so:
prefix = cls.session.query(Prefix.name).filter_by(pk=cls.prefix_fk).scalar()
Note: the cls.session is inherited from my base object similar to
Magic.py. (http://techspot.zzzeek.org/2011/05/17/magic-a-new-orm/)
This works great, until I go to add a second object... then the scalar
returns more than one and explodes.
I did a lot of reading, but just can't seem to make it work.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.