Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy declarative and MySQL specific data types

I have an already existing MySQL DB with many columns defined with MySQL specific column types (MEDIUMINT, TINYINT to mention a few), and even if the column type belongs to a standard SQL data type, sometimes is declared as unsigned.

Now I'm writing a Flask app to provide an API to access DB in various ways. Using plain SQLAlchemy, I would import specific data types definitions from sqlalchemy.dialects.mysql, like:

from sqlalchemy import Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.mysql import MEDIUMINT, TINYINT

Base = declarative_base()

class User(Base):
    id = Column(MEDIUMINT(unsigned=True), primary_key=True)

But I was told to use Flask-SQLAlchemy, so I'm declaring my tables like

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer**(???)**, primary_key=True)

How can I tell Flask-SQLAlchemy that the column id is a MySQL MEDIUMINT and that is unsigned? Can I pass, as the first argument to "db.Column" a data type definition imported not from "db.Something" but from sqlalchemy.dialects.mysql, and that would be a good practice (doesn't seem to me)?

Thank you ;)

like image 987
dappiu Avatar asked Apr 11 '14 13:04

dappiu


People also ask

What is Declarative in SQLAlchemy?

The Declarative system is the typically used system provided by the SQLAlchemy ORM in order to define classes mapped to relational database tables. However, as noted in Classical Mappings, Declarative is in fact a series of extensions that ride on top of the SQLAlchemy mapper() construct.

Can SQLAlchemy be used with MySQL?

SQLAlchemy supports MySQL starting with version 5.0. 2 through modern releases, as well as all modern versions of MariaDB.

What is difference between Flask-SQLAlchemy and SQLAlchemy?

One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API. Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult.


Video Answer


1 Answers

What's the problem with?

from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column
from sqlalchemy.dialects.mysql import MEDIUMINT, TINYINT

db = SQLAlchemy(app)

class User(db.Model):
    id = Column(MEDIUMINT(unsigned=True), primary_key=True)
like image 85
Mike Avatar answered Sep 18 '22 10:09

Mike