On Mon, Dec 1, 2014 at 4:09 AM, Steven DeVries <oni5...@gmail.com> wrote:
>     @classmethod
>     set_name(cls, instance):
>         prefix =
> cls.session.query(Prefix.name).filter_by(pk=instance.prefix_fk).scalar()
>         item =
> cls.session.query(Item.name).filter_by(pk=instance.prefix_fk).scalar()
>         suffix =
> cls.session.query(Suffix.name).filter_by(pk=instance.prefix_fk).scalar()
>         name = prefix.name + " "+ item.name + " " + suffix.name
>         instance.name = name
>     return
>
>
> I am not entirely sure what the cls does in the function.  I thought that it
> would let me access the instance of the object, but it does not appear to do
> that.  The change above, passing the instance of the class to the function,
> and doing the queries to the instance work as I expected.  Essentially, I
> thought cls was "self".

The "@classmethod" decorator marks the function as one that accepts
the *class* as the first parameter, not the instance. If you want the
instance as the first parameter, remove "@classmethod". Traditionally
in python, you would then rename the first parameter to "self".

> I am still interested if there is a way to automatically call this function
> at creation so that if I explicitly pass name="Some Legendary Item with a
> cool name", rather than leave it None, it will use the custom name, but
> otherwise auto-generate names based on the prefix, item, suffix.  I assume
> that would just be a custom __init__?    (Been using Declarative since that
> is what the ORM tutorial shows.)
>

Overriding the __init__ function is probably the most obvious way.
SQLAlchemy also has an "events" API which allows you to register
callback functions for various stages in the lifecycle of mapped
objects, sessions and so on. There is an "init" event that is
triggered when you construct your instance, but I'm not sure if it
happens before or after the default constructor:

http://docs.sqlalchemy.org/en/rel_0_9/orm/events.html#sqlalchemy.orm.events.InstanceEvents.init

There's also a "before_flush" event that is triggered when the Session
is about to flush changes to the database:

http://docs.sqlalchemy.org/en/rel_0_9/orm/events.html#sqlalchemy.orm.events.SessionEvents.before_flush

That event would be triggered any time the session was flushed, so
you'd need to iterate over the list of instances looking for instances
of your MagicItem class.

Hope that helps,

Simon

-- 
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 sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to