benjaminz benjaminz - 2 months ago 11
MySQL Question

How to create integer of a certain length with Sqlalchemy?

I've tried two approaches and both are not working, I searched on Google and didn't find any proper solutions. My code looks like:

intField = Column(SmallInt(), length=5)


And the error says:

Unknown arguments passed to Column: ['length']


I also tried, knowing it shouldn't work, this solution:

intField = Column(SmallInt(5))


And it does not work because this SqlAlchemy datatype doesn't accept arguments.

Any ideas?

[Update]

I'm using
MySQL
as database engine, so the solution here is to import mysql's own Integer type, and then specify the length I want it to be.

In the above example, I would only need to do:

from sqlalchemy.dialects import mysql

Integer = mysql.INTEGER

class ...
...
intField = Column(Integer(5))


But I still wonder if there is a more generic approach?

Answer

MySQL has the DECIMAL/NUMERIC type.

Use Decimal(5, 0) to a field with 5 digits.

Use this only if you really need a number. If won't do math with this field, prefer a String(5) and validate the digits (isdigit() is your friend).

In SQLAlchemy, handle it as a Numeric field.

Comments