Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting SQLAlchemy Error "__table_args__ value must be a tuple, dict, or None"

I have the following SQLAlchemy Model. It has been successfully migrated to the database:

class MyClassA(db.Model, Timestamp):
    a_id = db.Column(db.Integer, nullable=False, primary_key=True)
    b_id = db.Column(db.Integer, db.ForeignKey(C.c_id), nullable=False)
    d = db.Column(db.String(1024))
    e_id = db.Column(db.Integer,
                      db.ForeignKey(e.e_id))

Now I want to add a uniqueness constraint across the second and fourth fields. So I add the following line to the model:

     __table_args__ = db.UniqueConstraint('b_id', 'e_id', name='unique_constraint_bid_eid')

But now when I try to migrate it, I get the following error:

sqlalchemy.exc.ArgumentError: __table_args__ value must be a tuple, dict, or None

Why am I getting this error? And how can I fix it? I tried putting the right side of the equation in parenthesis, but that didn't fix it.

like image 650
Saqib Ali Avatar asked Nov 10 '16 07:11

Saqib Ali


2 Answers

table_args is supposed to be a tuple, dict, or None as the error code suggests. If you make it a tuple then you must put your value in parenthesis and also have a comma in there at the end:

try:

     __table_args__ = (db.UniqueConstraint('b_id', 'e_id', name='unique_constraint_bid_eid'), )
like image 113
Jeff Mandell Avatar answered Sep 17 '22 14:09

Jeff Mandell


refer this Table Configuration

Table arguments other than the name, metadata, and mapped Column arguments are specified using the table_args class attribute. This attribute accommodates both positional as well as keyword arguments that are normally sent to the Table constructor. The attribute can be specified in one of two forms. One is as a dictionary:

class MyClass(Base):
    __tablename__ = 'sometable'
    __table_args__ = {'mysql_engine':'InnoDB'}
    enter code here

The other, a tuple, where each argument is positional (usually constraints):

class MyClass(Base):
    __tablename__ = 'sometable'
    __table_args__ = (
            ForeignKeyConstraint(['id'], ['remote_table.id']),
            UniqueConstraint('foo'),
            )

Keyword arguments can be specified with the above form by specifying the last argument as a dictionary:

class MyClass(Base):
    __tablename__ = 'sometable'
    __table_args__ = (
            ForeignKeyConstraint(['id'], ['remote_table.id']),
            UniqueConstraint('foo'),
            {'autoload':True}
            )


like image 21
NicoNing Avatar answered Sep 18 '22 14:09

NicoNing