Two part question... I have a table of activity types . I want to
follow a ‘singleton pattern’ (ie. Only one instance of
‘run’,’jump’,’swim’ etc.). I have a get_or_create function on the
class that works as long as programmers using my module call:
   session.add( ActivityType.get_or_create(‘fly’))
   session.commit()

Question1: How can I modify my model/class shown below to either
prevent, or better yet, allow:
   session.add(ActivityType(‘fly’))
   session.commit()

Question2: (depending on answer above.) How can I ensure singleton if
my programmers do:
   a1 = ActivityType(‘fly’)
   a2 = ActivityType(‘fly’)
  session.add(a1)
  session.add(a2)
  session.commit()

Thanks or any guidance.
Rich

# Here is my table + class + mapper

tblActivityType = sa.Table('activitytype', metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('name', sa.String(128), nullable=False)
    )

class ActivityType(object):

    def __init__(self, name=None):
        self.name = name.lower()

    @staticmethod
    def get_or_create(tmpStr):
        _session = Session()

        mything =
_session.query(ActivityType).filter_by(name=tmpStr.lower() ).first()
        if mything is not None:
            return mything
        else:
            return ActivityType(tmpStr.lower())

mapper(ActivityType, tblActivityType)

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

Reply via email to