【发布时间】:2018-10-12 04:54:14
【问题描述】:
由于某种原因,当我使用 SQLAlchemy 的 union_all 和 .all() 时,它返回的项目数不正确。
正如您在下面看到的,我分解了每一个以查看错误所在。有谁知道为什么会发生这种情况?
>>> pn = PostNotification.query.filter_by(notified_id=1)
>>> cn = CommentNotification.query.filter_by(notified_id=1)
>>> pn.count()
4
>>> cn.count()
2
>>> u = pn.union_all(cn)
>>> u.count()
6
>>> all = u.all()
>>> len(all)
5
这是我的两个模型:
class NotificationMixin:
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150), nullable=False)
read = db.Column(db.Boolean, default=False)
created = db.Column(db.DateTime, index=True, default=datetime.utcnow)
@declared_attr
def notifier_id(cls):
return db.Column(db.Integer, db.ForeignKey('user.id'))
@declared_attr
def notified_id(cls):
return db.Column(db.Integer, db.ForeignKey('user.id'))
class PostNotification(db.Model, NotificationMixin):
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
comment_id = db.Column(db.Integer)
def __repr__(self):
return '<PostNotification {}>'.format(self.name)
class CommentNotification(db.Model, NotificationMixin):
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
comment_id = db.Column(db.Integer, db.ForeignKey('post_comment.id'))
def __repr__(self):
return '<CommentNotification {}>'.format(self.name)
更新:
Here is a screenshot of the data that represents the two models
当我明确定义列时,使用union_all 时没有问题。当我db.session.query(PostNotification) 和db.session.query(CommentNotification) 时,它只返回不正确的记录数。
pn = db.session.query(
PostNotification.id,
PostNotification.name,
PostNotification.read,
PostNotification.created,
PostNotification.post_id,
PostNotification.comment_id,
PostNotification.notifier_id,
PostNotification.notified_id).filter_by(
notified_id=1)
cn = db.session.query(
CommentNotification.id,
CommentNotification.name,
CommentNotification.read,
CommentNotification.created,
CommentNotification.post_id,
CommentNotification.comment_id,
CommentNotification.notifier_id,
CommentNotification.notified_id).filter_by(
notified_id=1)
u = pn.union_all(cn).order_by(PostNotification.created.desc())
>>> pn.count()
4
>>> cn.count()
2
u.count()
6
>>> all = u.all()
>>> len(all)
6
问题是我失去了模型,我的关系也消失了。因此,我必须使用这种非常丑陋的解决方法。这只有在您看到 https://i.stack.imgur.com/UHfo7.jpg 中的数据时才有意义。
result = []
for row in u:
if 'post' in row.name.split('_'):
n = PostNotification.query.filter_by(id=row.id).first()
result.append(n)
if 'comment' in row.name.split('_'):
n = CommentNotification.query.filter_by(id=row.id).first()
result.append(n)
现在我的result 按降序排列,两个表通过union_all 合并,我的关系恢复正常。现在的问题是,我显然不能使用 result.paginate,因为result 现在是list。
【问题讨论】:
-
感谢您的建议。我编辑了我的问题。
标签: python sqlalchemy flask-sqlalchemy