On Jan 12, 2010, at 4:17 AM, Chris Withers wrote:

> Hi All,
> 
> We have a lot of declarative-mapped classes that have a method that looks 
> like:
> 
>    @classmethod
>    def find_or_create(cls, session, name):
>        result = session.query(cls).filter_by(name=name).first()
>        if result is None:
>            result = cls(name=name)
>            session.add(result)
>        return result
> 
> This feels clunky to me:
> 
> 1 - duplicate code on each class (there are a lot of classes!)

seems like a function you'd only need once, on a base class or similar.  


> 
> 2 - feels like something that SA might provide itself

does SQLA assume that all mapped objects have a field called "name" and are 
retrieved using a filter on a single column ?   the above is too specific to 
your use case.    The "general" purpose version of such a function would 
require writing out the whole query in a callable anyway so it doesn't make 
things any simpler than just using python.

find_or_create() is also not very performant in the case where you're better 
off loading a whole set of rows first, so not a default the core needs to be 
recommending.

merge() exists because its based around the concept of the identity map, which 
is why primary key is special.

> 
> OK, so why not put it in a base class? 'cos Declarative doesn't like base 
> classes that don't map to a table, and writing a metaclass for this feels 
> heinous...

declarative_base accepts an existing class, which you can apply whatever 
lookups and such before turning it into a declarative base.   Writing a 
metaclass is also a good way go, for the purposes of extending declarative to 
do what you want, not provide the actual find_or_create, which you still can 
put on a subclass.   The recipe at 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DeclarativeMixins illustrates 
this concept which is straightforwardly adaptable to your use case.


--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to [email protected].
For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to