在SQLAlchemy中的多对多关系上设置NOT NULL约束

时间:2016-05-12 12:55:29

标签: python postgresql sqlalchemy

我有两个通过关联模型相关的模型,所有模型都是使用SQLAlchemy' s declarative_base()定义的。

class P(Base):
    p_id = Column(Integer, primary_key=True)
    foo = Column(String)
    bar = Column(String)

class Q(Base):
    q_id = Column(Integer, primary_key=True)
    x = Column(String)
    y = Column(String)

class PQ(Base):
    p_id = Column(Integer, primary_key=True, ForeignKey('p.p_id', match='FULL', primary_key=True)
    q_id = Column(Integer, primary_key=True, ForeignKey('q.q_id', match='FULL', primary_key=True)
    additional_data = Column(String)

    p = relationship('P', backref='qs')
    q = relationship('Q', backref='ps')

现在这可以按预期工作,但我还要强制要求每个P 必须与至少一个Q

相关联
 p = P()
 p.p_id = 123
 p.save()  # this should throw an exception saying that some constraint is being violated
 session.rollback()
 q = Q()
 q.q_id = 789
 p.qs = [q]
 p.save()  # this should work

如何使用SQLAlchemy强制执行此操作?

0 个答案:

没有答案