Search code examples
sqlalchemy

SqL alchemy .first() issue


Here is my Python class where I am defining a table data I'm facing an issue with querying a Python class in SQLAlchemy. Here's my code:

class Vouchers(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     percentage = db.Column(db.Float, nullable=False)
     voucher = db.Column(db.String(80), unique=True)
     voucher_type = db.Column(db.String(10), nullable=False)
     voucher_states = db.Column(db.JSON, nullable=False)

Here is the data which is stored in this table

| id | percentage | voucher | voucher_type | voucher_state |
|----|------------|---------|--------------|---------------|
| 3  | 500        | hfd4775 | simple       | \[Wisconsin\]   |

The issue is when I search like this voucher_exist = Vouchers.query.filter_by(voucher=0).first()

It returns the above voucher with ID 3, which it should not return. What could be the issue? can anyone explain the possible issue with it and why i am getting first row?


Solution

  • What could be the issue? can anyone explain the possible issue with it and why i am getting first row?

    The issue is that you're using MySQL. MySQL is perfectly happy to check for equality between a string and an integer... by converting the string to an integer, and that conversion resulting in the integer 0 if the string is not in any way an integer:

    > select 'hfd4775' = 0;
    1
    > select * from vouchers where voucher = 0;
    3   500 hfd4775 simple