我想为包含计数的模型创建一个属性.
因为我总是需要的财产,我想使查询与JOIN类似sqlalchemy.orm.relationship与lazy='joined'
例如,我定义了如下的模型
import sqlalchemy as s, func
from sqlalchemy.orm import relatioship
# ...
class Foo(Base):
__tablename__ = 'foo'
id = s.Column(s.Integer, primary_key=True)
bar_id = s.Column(s.Integer, s.ForeignKey('bar.id'))
bar = relationship('Bar')
class Bar(Base):
__tablename__ = 'bar'
id = s.Column(s.Integer, primary_key=True)
@property
def foo_count(self):
return Foo.query.filter_by(bar=self).count()
Run Code Online (Sandbox Code Playgroud)
当我访问属性时foo_count,它会向DBMS发送查询.
因为我总是访问这个属性,我想急切地加载它这样的计数属性
# Not session.query(Bar, func.count(Foo.id)).join(Foo) ...
bar = Bar.query.first()
Run Code Online (Sandbox Code Playgroud)
SQL将是这样的
SELECT id, COUNT(Foo.id)
FROM bar
INNER JOIN foo
ON bar.id = foo.id
Run Code Online (Sandbox Code Playgroud)
然后bar.foo_count就不会发生SQL查询.
我该如何制作一个属性foo_count?
我在PostgreSQL中使用sqlalchemy。我是sqlalchemy的新手。
我为名为“ to_user_id”的模型“ User”创建了外部密钥,以对“ Invitation”进行建模,该密钥不可为空。
当我尝试使用删除模型“用户”的实例时
session.delete(user)
Run Code Online (Sandbox Code Playgroud)
sqlalchemy会在删除之前自动将邀请的to_user_id设置为NULL,而PostgreSQL则会引发以下错误。
IntegrityError: (IntegrityError) null value in column "to_user_id" violates not-null constraint
Run Code Online (Sandbox Code Playgroud)
如何禁用它?
这是我模型的定义
class User(Base):
'''
User model
'''
__tablename__='User'
id = Column(Integer,primary_key=True)
class Invitation(Base):
'''
Invitation model
'''
__tablename__ = 'Invitation'
__table_args__ = (UniqueConstraint('appointment_id', 'to_user_id'),)
id = Column(Integer, primary_key=True)
appointment_id = Column(Integer,ForeignKey('Appointment.id',
ondelete='CASCADE'), nullable=False)
appointment = relationship('Appointment', backref=backref('invitations'),
)
from_user_id = Column(Integer,ForeignKey('User.id',
ondelete='SET NULL'), nullable=True)
from_user = relationship('User', backref=backref('sent_invitations'),
primaryjoin='Invitation.from_user_id==User.id')
to_user_id = Column(Integer,ForeignKey('User.id',
ondelete='CASCADE'), nullable=False)
to_user = relationship('User',backref=backref('received_invitations'),
primaryjoin='Invitation.to_user_id==User.id',
)
Run Code Online (Sandbox Code Playgroud)