Home > Software engineering >  Peewee Foreign Key is not an integer
Peewee Foreign Key is not an integer

Time:12-10

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

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. 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'

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

Where did I make a mistake?

CodePudding user response:

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 it's a player you can get its id attribute to compare.

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.

CodePudding user response:

Internally the foreign key is an integer. But Peewee automatically gets the Player object for you from that foreign key, so club_data.owner is that object. To get the ID, you need to access its .id attribute.

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