On Thu, Mar 4, 2010 at 2:31 PM, Daniel Robbins <drobb...@funtoo.org> wrote: > Hi All, > > I have created a base declarative object that has a pre-made primary > key, so I don't have to add it to all my child tables:
I figured out how to do this, using the following code: seqnum=0 def PrimaryKey(seqprefix=None): global seqnum if not seqprefix: seqnum += 1 seqname = "id_seq_%s" % seqnum else: seqname = "%s_id_seq" % seqprefix return Column(Integer, Sequence(seqname, optional=True), primary_key=True) class ClassDefaults(DeclarativeMeta): def __init__(cls,classname, bases, dict_): if not ( dict_.has_key('__mapper_args__') and dict_['__mapper_args__'].has_key('polymorphic_identity') ): # Only add the key if we are not creating a polymorphic SQLAlchemy object, because SQLAlchemy # does not want a separate 'id' key added in that case. # seqprefix can be None seqprefix = getattr(cls,'__tablename__',None) dict_['id'] = PrimaryKey(seqprefix=seqprefix) return DeclarativeMeta.__init__(cls, classname, bases, dict_) Base = declarative_base(metaclass=ClassDefaults) class Location(Base): __tablename__ = 'location' parent_id = Column(Integer, ForeignKey('location.id')) parent = relation('Location', backref=backref('children'), remote_side='location.c.id') name = UniqueString(25) desc = Column(String(80)) This code above allows my adjacency list table Location to be handled correctly, and also allows my Single Table inheritance (not included in the above code) to work too. The PrimaryKey() function will generate numerically increasing sequence names with no argument, or a specific sequence name if supplied with an argument. ClassDefaults calls it with the __tablename__ if one is available to create a sequence that has a name similar to the underlying table (with a "_seq" suffix.) Regards, Daniel -- 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.