[英]Peewee Foreign Key is not an integer
我尝试与整数进行比较,但 ForeignKey 值不是 integer:
class Player(Model):
id = IntegerField(primary_key=True)
first_name = CharField(max_length=32)
class Meta:
database = db
db_table = "player"
class Club(Model):
id = IntegerField(primary_key=True)
owner = ForeignKeyField(Player, backref='owner')
class Meta:
database = db
db_table = "club"
现在我尝试将当前session["id"]
与数据库中的所有者进行比较:
club_data = Club.get(Club.id == id)
if session["id"] == club_data.owner:
do_some_things()
值club_data.owner
不是 integer。 我在数据库文件上犯了错误吗?
当我尝试int(club_data.owner)
时,我收到以下错误消息: int() argument must be a string, a bytes-like object or a number, not 'Player'
print(club_data.owner) is 0 and session["id"] is also 0
我在哪里做错了?
您可能想要if session["id"] == club_data.owner.id
,因为您的第二个错误表明club_data.owner
的类型为Player
,而不是int
。 如果是玩家,您可以获取其id
属性进行比较。
作为说明,这是:
print(club_data.owner) is 0 and session["id"] is also 0
不会按照你的想法去做。 print()
将返回不为0
的None
,因此比较 ( is
),同时也抛出警告将永远不会评估为 True。
在内部,外键是 integer。 但是 Peewee 会自动从该外键为您获取Player
object,因此club_data.owner
是 object。 要获取 ID,您需要访问其.id
属性。
if session['id'] == club_data.owner.id:
do_some_things()
其他回答者都在正确的轨道上,但遍历外键会导致额外的查询 --- 没有必要只比较 ID:
club_data = Club.get(Club.id == id)
# Replace '.owner' with '.owner_id':
if session["id"] == club_data.owner_id:
do_some_things()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.