SqlAlchemy:如何处理所需的循环外键

时间:2018-02-18 12:18:55

标签: python sql postgresql sqlalchemy

我想为一个拥有许多地址的用户建模,并且能够拥有一个" primary"地址。

我试图通过制作所需的primary_address_id来严格保证用户必须至少拥有一个地址。我也不希望没有孤立的地址,因此也需要Address.user_id

class User(db.Model):
    __tablename__ = 'Users'
    id = Column(Integer, primary_key=True)
    primary_address_id = Column(Integer, ForeignKey('Addresses.id'), nullable=False)

    primary_address = relationship(Address, primaryjoin=primary_address_id == Address.id, foreign_keys=primary_address_id)
    addresses = relationship(Address, primaryjoin=id == Address.building_id, foreign_keys=Address.building_id)

class Address(db.Model):
    __tablename__ = 'Addresses'

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('Users.id'), nullable=False)

当我尝试以下插入具有单个地址的用户时,它会失败,因为primary_address_id为None。

user = User()
address1.user = user
user.addresses = [address1]
user.primary_address = address1

session.add_all([address1, user])

session.commit()
  

cursor.execute(语句,参数)          sqlalchemy.exc.IntegrityError:(psycopg2.IntegrityError)列中的空值" primary_address_id"违反非空约束           [SQL:' INSERT INTO"用户" (primary_address_id)VALUES(%(primary_address_id)s)RETURNING"用户" .id'] [参数:   {' primary_address_id':无}](有关此错误的背景信息:   http://sqlalche.me/e/gkpj

SqlAlchemy和Postgres是否有解决鸡蛋问题的方法而不必让一方可以为空?另外,还有另一种方法可以用相同的参考要求对其进行建模吗?

0 个答案:

没有答案