sqlalchemy autoincrement值为外键mysql

时间:2014-12-16 04:43:31

标签: python mysql sqlalchemy auto-increment foreign-key-relationship

我试图在其他表中使用自动增量唯一ID字段作为外键。我的模型如下:

class User(Base):
        __tablename__ = 'Users'

        uid = Column(INT, primary_key=True, autoincrement=True)
        name = Column(TEXT)
        email = Column(TEXT)
        dateRegistered = Column(TIMESTAMP)
        phone = Column(TEXT)

class AddressMap(Base):
        __tablename__ = 'AddressMaps'

        uid = Column(INT, primary_key=True, autoincrement=True)
        userId = Column(INT, ForeignKey('Users.uid'))
        addressId = Column(INT, ForeignKey('Addresses.uid'))
        dateCreated = Column(TIMESTAMP)


        user = relationship("User", backref=backref('AddressMaps'))
        address = relationship("Address", backref=backref('AddressMaps'))

class Address(Base):
        __tablename__ = 'Addresses'

        uid = Column(INT, primary_key=True, autoincrement=True)
        street = Column(TEXT)
        city = Column(TEXT)
        state = Column(TEXT)
        postal = Column(TEXT)
        dateRegistered = Column(TIMESTAMP)

我的问题是,当我创建用户对象时,它不是使用uid值创建的。我理解这是因为该对象尚未提交到数据库。问题是,由于User对象的uid值为None,我无法将AddressMap对象链接到它。

在SQLAlchemy中处理此问题的惯用方法是什么?

1 个答案:

答案 0 :(得分:3)

你不应该需要一个uid。由于您已在表之间创建了关系,因此您可以向用户添加AddressMap对象:

samantha = User(name='Sam', email='sam@xyz.abc', phone='555-555-5555')

您现在可以访问samantha.AddressMaps集合(请参阅backref表格中user关系下的AddressMap。您可以将AddressMap个对象添加到此集合中:

samantha.AddressMaps = [AddressMap(dateCreated=datetime.now()),
                        AddressMap(dateCreated=datetime.min)]

现在,您可以将这些对象添加到sessioncommit。有关详细信息,请参阅the docs

顺便提一下,就像一个FYI,you don't need to include autoincrement=True在表的第一个整数列上。