The columns of the primary key must be in specific order.
I see some code from document :
class User(Base):
__tablename__ = 'users'
id = Column(Integer)
__mapper_args__ = {
'primary_key':[id]
}
But it just does not work (I'm using mysql, and the id primary key will not be generated). Any possible solutions?
For defining a PRIMARY KEY constraint on multiple columns, use the SQL syntax given below. CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME) );
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
MySQL Composite Primary Key Index You can create an index for composite primary key that uses the same fields present in your composite primary key. mysql> alter table new_orders ADD INDEX new_index (order_id, product_id); Hopefully, now you can create composite primary key in MySQL.
Primary Key Declaration In a table, there can only be one primary key. A primary key can have one or as many columns as possible.
In case columns are declared in the same order as they should be in the primary key:
class User(Base):
field1 = Column(Integer, primary_key=True)
field2 = Column(Integer, primary_key=True)
Otherwise declare it in __table_args__
:
class User(Base):
field1 = Column(Integer)
field2 = Column(Integer)
__table_args__ = (
PrimaryKeyConstraint(field2, field1),
{},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With