alice
alice

Reputation: 63

Sqlalchemy: Why does querying with a string primary key work for an primary key of type integer?

My model is defined so that the primary key is an integer

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
   email = db.Column(db.String(100), nullable=False)
   password_hash = db.Column(db.String(200), nullable=False)

Both of these return a user correctly:

User.query.get("1")
User.query.get(1)

Why am I able to use a string to query an integer column? From the docs: A scalar, tuple, or dictionary representing the primary key. -> does string count as a scalar? I'm not sure what scalar means in this context.

I am using a MySql database.

Upvotes: 0

Views: 599

Answers (1)

nbk
nbk

Reputation: 49375

This makes mysql automatically, see manual

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts strings to numbers as necessary, and vice versa.

Upvotes: 0

Related Questions