Many-to-one relationship in SQLAlchemy

Posted by Arrieta on Stack Overflow See other posts from Stack Overflow or by Arrieta
Published on 2010-06-01T17:49:57Z Indexed on 2010/06/01 17:53 UTC
Read the original article Hit count: 161

This is a beginner-level question.

I have a catalog of mtypes:

mtype_id name
       1 'mtype1'
       2 'mtype2'
[etc]

and a catalog of Objects, which must have an associated mtype:

obj_id mtype_id name
     1        1 'obj1'
     2        1 'obj2'
     3        2 'obj3'
[etc]

I am trying to do this in SQLAlchemy by creating the following schemas:

mtypes_table = Table('mtypes', metadata,
 Column('mtype_id', Integer, primary_key=True),
 Column('name', String(50), nullable=False, unique=True),
)

objs_table = Table('objects', metadata,
 Column('obj_id', Integer, primary_key=True),
 Column('mtype_id', None, ForeignKey('mtypes.mtype_id')),
 Column('name', String(50), nullable=False, unique=True),
)

mapper(MType, mtypes_table)
mapper(MyObject, objs_table, 
 properties={'mtype':Relationship(MType, backref='objs', cascade="all, delete-orphan")}
)

When I try to add a simple element like:

mtype1 = MType('mtype1')
obj1 = MyObject('obj1')
obj1.mtype=mtype1
session.add(obj1)

I get the error:

AttributeError: 'NoneType' object has no attribute 'cascade_iterator'

Any ideas?

© Stack Overflow or respective owner

Related posts about python

Related posts about database-design