-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On Jul 30, 2012, at 7:47 PM, Adam Tauno Williams wrote:
> I have two classes Contact and CompanyInfo that should exist in a 1:1
> relation; CompanyInfo contains a comment related to Contact. This works
> -
>
> class Contact(Base, KVC):
> ...
> _info = relation( 'CompanyInfo',
> uselist = False,
> backref = backref( 'company_info_contact' ),
> primaryjoin =
> ( 'CompanyInfo.parent_id==Contact.object_id' ) )
>
>
> comment = association_proxy( '_info', 'text', )
>
> - so that the "text" value of the CompanyInfo object is presented as the
> "comment" value of the Contact. This is awesome! [The database
> is-the-way-it-is, other apps use it this way, I can't change it].
>
> Only caveat is if you somehow [those darn other apps...] end up with a
> Contact with no corresponding CompanyInfo object. Then accessing
> Contact.comment bombs out.
>
> Is there anyway to get the SQLalchemy model to automatically create a
> CompanyInfo object if one is missing?
Well....the most brute force way would be to use customizing features on the
association_proxy to do so, though I'd have to read it's source code to see if
there's a path to doing that and it would likely be ugly.
A much quicker way would be to just make "text" into a @property that returns
"self._text", and the association prox would be returning "_text_. It could
do the job of sticking a "CompanyInfo" on the object. Downside of this is, a
little bit of method latency.
But really, if you're going to make a @property, and this is a scalar
relationship anyway, I'm not sure what the win of assocation_proxy is in the
first place, just do a descriptor directly:
class Contact(...):
# ...
@property
def comment(self):
if self._info is None:
self._info = CompanyInfo(text="")
return self._info.text
@comment.setter
def comment(self, value):
if self._info is None:
self._info = CompanyInfo(text=value)
else:
self._info.text = value
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (Darwin)
Comment: GPGTools - http://gpgtools.org
iQEcBAEBAgAGBQJQFx8YAAoJEDMCOcHE2v7heJMH/jMz8R9oDNOLFbQaPQfyCvMs
tqVDTJxRMIF9GZB3Stbr+j62NXoaJyGpoGvoyDC0XLRTZ5Awf4Brpoak+r8Jb68s
hveVOHfI8VmysG2O9tKiZxI7JaUpUKQwm0Dx7PUgtxQSyeonE6UlBIKblCZbKyLe
uJlWNlB5y1DrGl9UnGVmK2GkiAC6SdEtp7T+fXdE3SKiiLas6QmgjExFJrecgfRm
Ohyvx3k/n50CW6l1AfDYrn5G3PIpPGIxOnOF48897p1AcQPvVwK8RQR2fz/GOUCW
JcXeu1QsYNtTP8owVpvFf5XzpiQHvWuI3aCBpMF52itxvXHSN5CrQ8qRgIgolek=
=qpjK
-----END PGP SIGNATURE-----
--
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.