On Jun 21, 2008, at 11:38 AM, Werner F. Bruhin wrote:

> Looking at
> "http://www.sqlalchemy.org/docs/05/ormtutorial.html#datamapping_declarative 
> "
> it would be really nice if the "init" and "repr" methods are
> automagically generated, or maybe something like a mixin could be  
> provided.

declarative already does generate a keyword-based "__init__" method if  
none is present.   variations on this theme, including __repr__, are  
trivial for end users to create as base classes (note that declarative  
supports a user-defined base class, use the 'cls' argument to  
declarative_base()).

> The debug problem (see traceback below) I had is due to the code I  
> used
> from the wiki:
> http://www.sqlalchemy.org/trac/wiki/UsageRecipes/GenericOrmBaseClass
>
> The code does not work in 0.5 anymore, one reason is that the  
> MyClass.c
> attribute is no longer there.

The usage of "self.c" there is broken in any version;  it does not  
account for attributes on the instance which are renamed based on the  
column, and also does not account for any relation-based attributes.   
That's the entire point of there being a "mapper()" that is distinct  
from a "Table".

My preference on a custom __init__ is just :

def __init__(self, **kwargs):
     for k in kwargs:
         setattr(self, k, kwargs[k])

Since I think the assumption that "every kwarg must match a mapped  
attribute" is naive; theres plenty of non-mapped attributes an object  
might have.

But if you really want to match them against the mapping, do it  
against what the mapping says, not the table:

def __init__(self, **kwargs):
     mapper = object_mapper(self)
     for k in kwargs:
         if not mapper.get_property(k, raiseerr=False):
             raise Exception("no such attribute %s" % k)
         setattr(self, k, kwargs[k])


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
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