【问题标题】:Peewee Foreign Key is not an integerPeewee 外键不是整数
【发布时间】:2021-12-09 22:36:53
【问题描述】:

我尝试与整数进行比较,但 ForeignKey 值不是整数:

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 不是整数。我在数据库文件上犯了错误吗?

当我尝试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

我在哪里做错了?

【问题讨论】:

    标签: python peewee


    【解决方案1】:

    您可能想要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() 将返回 None 而不是 0,因此比较 (is),同时也抛出警告永远不会评估为 True。

    【讨论】:

      【解决方案2】:

      在内部,外键是一个整数。但是 Peewee 会自动从该外键为您获取 Player 对象,因此 club_data.owner 就是该对象。要获取 ID,您需要访问其 .id 属性。

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

      【讨论】:

        【解决方案3】:

        其他回答者都在正确的轨道上,但是遍历外键会导致额外的查询 --- 没有必要只比较 ID:

        club_data = Club.get(Club.id == id)
        # Replace '.owner' with '.owner_id':
        if session["id"] == club_data.owner_id:
            do_some_things()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-17
          • 1970-01-01
          • 1970-01-01
          • 2018-12-07
          相关资源
          最近更新 更多