> 
> And replace it with something like this:
>     class Keyword(Base):
>         .... snip  (same as before) ....
>     
>     class Foo(Base):
>         .... snip  ....
>         keywords = generate_many_to_many_for_me('Foo', 'Keyword')

>> there's a recipe for this at this blog post, you might consider building
on it's general example:
http://techspot.zzzeek.org/2011/05/17/magic-a-new-orm/
>> the missing link is to just use mapping events to set things up at the
appropriate time.


Michael,
Your cats are awesome! I remember reading this the day you put it out there,
but I just didn't understand it at the time. I've been going over this and
now I understand it perfectly! Any chance of pulling some of this back into
sqlalchemy? many_to_many alone saves quite a bit of boilerplate code. 


The only change I made was to let many_to_many set up default local / remote
columns on the secondary table so you can just do:

    class Video(Base):
        keywords = many_to_many("Keyword", "video_keyword")

    class many_to_many(DeferredProp):
        """Generates a many to many relationship."""

        def __init__(self, target, tablename, **kw):
            self.target = target
            self.tablename = tablename
            self.local = kw.get('local')
            self.remote = kw.get('remote')
            self.kw = kw

        def _config(self, cls, key):
            """Create an association table between parent/target
            as well as a relationship()."""

            target_cls = cls._decl_class_registry[self.target]
            local_pk = list(cls.__table__.primary_key)[0]
            target_pk = list(target_cls.__table__.primary_key)[0]

            if not self.local:
                self.local = cls.__tablename__.lower() + "_id"
            if not self.remote:
                self.remote = target_cls.__tablename__.lower() + "_id"

            t = Table(
                    self.tablename,
                    cls.metadata,
                    Column(self.local, ForeignKey(local_pk),
primary_key=True),
                    Column(self.remote, ForeignKey(target_pk),
primary_key=True),
                    keep_existing=True
                )
            rel = relationship(target_cls,
                    secondary=t,
                    collection_class=self.kw.get('collection_class', set)
                )
            setattr(cls, key, rel)
            self._setup_reverse(key, rel, target_cls)



Thanks,
Jeff Peck


-- 
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/groups/opt_out.

Reply via email to