gpt4 book ai didi

python - 如何查看用户是否不是多对多关系?

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:39 24 4
gpt4 key购买 nike

所以我想知道如何查看用户是否不处于多对多关系中。这是我当前的代码:

seen = db.Table("seen", db.Column("user_id", db.Integer, db.ForeignKey("user.id")), db.Column("match_id", db.Integer, db.ForeignKey("user.id")))

//

seenmatch = db.relationship("User", secondary=seen, primaryjoin=(seen.c.user_id == id), secondaryjoin=(seen.c.match_id == id), backref=db.backref("seenmatches", lazy="dynamic"), lazy="dynamic")

//

users = User.query.filter_by(gender=gender).filter(or_(User.height == height, User.grade == grade)).filter(User.username != current_user.username).filter(seen.c.user_id != current_user.id).limit(10).all()

.filter(seen.c.user_id != current_user.id)

上面的粗体部分是我正在尝试处理的内容。我想要完成的是显示 10 个用户或用户的匹配项。当用户刷新页面时,不应再次看到相同的匹配项。为了确保用户不会再次看到其他匹配项,我添加了多对多关系。唯一的问题是让过滤器正常工作,不显示已经见过的用户。当我运行这段代码时,它根本没有显示任何用户。如果有人可以帮助我,我将不胜感激!

最佳答案

您想要的被称为反连接。您可以通过两个简单的步骤来实现:

  • 首先,使用辅助条件 seen.c.user_id == current_user.id 执行从 Userseen 的外连接。这样,当前用户已经看到的用户将填充 seen 列,而所有其他用户的列将为空。
  • 然后过滤出 seen 列为空的用户。

所以,像这样:

User.query \
.outerjoin(seen, (User.id == seen.c.match_id)
& (seen.c.user_id == current_user.id)) \
.filter(seen.c.user_id == None)

关于python - 如何查看用户是否不是多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com