On 8/7/15 2:10 PM, buch...@gmail.com wrote:
Hi there,

I'm trying to do something pretty weird. I have SQLAlchemy instrumented classes that extend a class in addition to Base, like so:

class Region(Base, t_Region):
    __tablename__ = 'region'
    id = Column(
        mysql.INTEGER(11),
        primary_key=True,
        nullable=False,
        autoincrement=True,
        index=True,
        unique=True)
    name = Column(
        mysql.VARCHAR(64),
        nullable=False,
        index=True,
        default='',
        unique=True)

This works great for reads because I can return it anywhere a t_Region is expected and everything does what it is supposed to.

But now I can't figure out how to do the reverse; for example, I have a t_Region object, and I want to insert it into the database. So far I've got this:

mapped = Region(**region.__dict__)

This works, but it lacks elegance as it creates another object.

I'd go with that, or more likely a dedicated constructor (and I'd never just yank __dict__ like that for schema-defined objects):

from sqlalchemy import inspect

class Region(...):

    @classmethod
    def as_region(cls, other):
        kw = dict(
(key, getattr(other, key)) for key in inspect(cls).attrs.keys() if hasattr(other, key)
        )
        return Region(**kw)

as it is the simplest. Ideally you'd not use raw t_Region objects and instead use an appropriate factory pattern to create the Region object up front - it's this lack of "elegance" that ultimately leads to other elegance-lacking things like having to copy the object to the type you want.

--
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