-1

I'm currently trying to create an ORM model in Peewee for an application. However, I seem to be running into an issue when querying a specific model. After some debugging, I found out that it is whatever below a specific model, it's failing.

I've moved around models (with the given ForeignKeys still being in check), and for some odd reason, it's only what is below a specific class (User).

def get_user(user_id):
    user = User.select().where(User.id==user_id).get()
    return user

class BaseModel(pw.Model):
    """A base model that will use our MySQL database"""
    class Meta:
        database = db


class User(BaseModel):
    id = pw.AutoField()
    steam_id = pw.CharField(max_length=40, unique=True)
    name = pw.CharField(max_length=40)
    admin = pw.BooleanField(default=False)
    super_admin = pw.BooleanField()

#...

I expected to be able to query Season like every other model. However, this the peewee error I run into, when I try querying the User.id of 1 (i.e. User.select().where(User.id==1).get() or get_user(1)), I get an error returned with the value not even being inputted.

UserDoesNotExist: <Model: User> instance matching query does not exist:
SQL: SELECT `t1`.`id`, `t1`.`steam_id`, `t1`.`name`, `t1`.`admin`, `t1`.`super_admin` FROM `user` AS `t1` WHERE %s LIMIT %s OFFSET %s
Params: [False, 1, 0]

Does anyone have a clue as to why I'm getting this error?

Phlex
  • 401
  • 2
  • 6
  • 17

2 Answers2

0

Read the error message. It is telling you that the user with the given ID does not exist.

Peewee raises an exception if the call to .get() does not match any rows. If you want "get or None if not found" you can do a couple things. Wrap the call to .get() with a try / except, or use get_or_none().

http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.get_or_none

coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Sorry, I'm rather new to this, but then why does `User.get(1)` return the proper value (user ID of 1), while the other `User.select().where(User.id==1).get()` returns nothing, with params `[False, 0, 1]`? I understand the 0 and 1 are for limit and offset, but it seems the `User.id==1` is evaluating as a boolean, and sending in `False` instead of an expression to evaluate in the query. Is this correct? If so, why is it giving `False` as a param? But, I will definitely be using the get_or_none() since I did come across that after posting this question! – Phlex Sep 14 '19 at 17:04
-1

Well I think I figured it out here. Instead of querying directly for the server ID, I just did a User.get(1) as that seems to do the trick. More reading shows there's a get by id as well.

Phlex
  • 401
  • 2
  • 6
  • 17