On 12/3/05, Brian Beck <[EMAIL PROTECTED]> wrote:
>
> Mike Orr wrote:
> > Chemical:
> >     canonical_name = ForeignKey("Name")
> >     names = RelatedJoin("Name")
> >
> > Name:
> >     name = StringCol(notNone=True)
> >     chemicals = RelatedJoin("Chemical")
>
> > The other annoyance is chemical.canonical_name and chemical.names are
> > records rather than just the string names, so I have to dereference
> > them again: chemical.canonical_name.name .  But the Name table has
> > only one "interesting" field, and the same for five other M:M
> > relations I have.  I guess I could rename the attributes and use
> > properties to make .canonical_name and .names look like strings, but
> > propagating changes to .names back to the database would be
> > complicated.
>
> SQLObject makes doing this less of a pain than it sounds.
>
> class Chemical(SQLObject):
>   canonical_record = ForeignKey("Name")
>
>   def _get_canonical_name(self):
>     return self.canonical_record.name
>
>   def _set_canonical_name(self, value):
>     self.canonical_record.name = value
>
> ...

Thanks, but .names?

def _set_names(self, value):
    # 'value' is ['A', 'B', 'C']
    # Look up current values
    # Delete unrecognized values
    # Add missing values

Regarding the other thread about not having duplicate values in a M:M
relationship, shouldn't that be the default?

For solving the do-I-want-to-retrieve-or-insert problem, I came up
with this, which I'll test on Monday.  We may want to add the method
to SQLObject since it's such a common situation.

GetOrCreateMixin:
    def getOrCreate(self, field, value, **create_args):
        selector = getattr(self.q, field)
        try:
            return self.select(selector=value).next()
        except StopIteration:
            return self(field=value, **create_args)

('create_args' would not be necessary if the table has only one non-id
field, but you could pass the connection or id value or whatever else
you need.)

--
Mike Orr <[EMAIL PROTECTED]>
([EMAIL PROTECTED] address is semi-reliable)

Reply via email to