我正在尝试在其他表中将自动递增的唯一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值创建的。我理解这是因为对象尚未提交到数据库。问题是,由于用户对象没有uid值,所以我无法将AddressMap对象与其链接。
在SQLAlchemy中,处理这个问题的惯用方法是什么?

最佳答案

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

samantha = User(name='Sam', email='[email protected]', 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在表的第一个整数列上。

关于python - sqlalchemy自动增量值作为外键mysql,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27497666/

10-12 12:33