Saqib Ali
Saqib Ali

Reputation: 12645

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.

Upvotes: 8

Views: 11807

Answers (2)

NicoNing
NicoNing

Reputation: 3242

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}
            )


Upvotes: 9

Jeff Mandell
Jeff Mandell

Reputation: 863

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'), )

Upvotes: 19

Related Questions