简体   繁体   English

Peewee 外键不是 integer

[英]Peewee Foreign Key is not an integer

I try to compare to integers but the ForeignKey Value isn't 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"

Now I try to compare the current session["id"] with the owner from the database:现在我尝试将当前session["id"]与数据库中的所有者进行比较:

club_data = Club.get(Club.id == id)
if session["id"] == club_data.owner:
    do_some_things()

The value club_data.owner isn't an integer.club_data.owner不是 integer。 Did I make a mistake on the Database file?我在数据库文件上犯了错误吗?

When I try int(club_data.owner) , I get the following error message: int() argument must be a string, a bytes-like object or a number, not 'Player'当我尝试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

Where did I make a mistake?我在哪里做错了?

You probably want if session["id"] == club_data.owner.id , since your second error suggests that club_data.owner has the type Player , not int .您可能想要if session["id"] == club_data.owner.id ,因为您的第二个错误表明club_data.owner的类型为Player ,而不是int If it's a player you can get its id attribute to compare.如果是玩家,您可以获取其id属性进行比较。

As a note, this:作为说明,这是:

print(club_data.owner) is 0 and session["id"] is also 0

Is not going to do what you think.不会按照你的想法去做。 print() will return None which is not 0 , so the comparison ( is ), while also throwing a warning will not ever evaluate to True. print()将返回不为0None ,因此比较 ( is ),同时也抛出警告将永远不会评估为 True。

Internally the foreign key is an integer.在内部,外键是 integer。 But Peewee automatically gets the Player object for you from that foreign key, so club_data.owner is that object.但是 Peewee 会自动从该外键为您获取Player object,因此club_data.owner是 object。 To get the ID, you need to access its .id attribute.要获取 ID,您需要访问其.id属性。

if session['id'] == club_data.owner.id:
    do_some_things()

The other answerers are on the right track, but traversing the foreign-key will result in an extra query --- which is unnecessary to just compare the ID:其他回答者都在正确的轨道上,但遍历外键会导致额外的查询 --- 没有必要只比较 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM