Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a table class that contains multi-column primary key?

Tags:

sqlalchemy

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?

like image 387
Determinant Avatar asked Jan 27 '12 13:01

Determinant


People also ask

How do you declare multiple columns as primary key?

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

Can a table have multiple columns as primary key?

A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

How can I create multiple primary keys in MySQL table?

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.

Can primary key have 3 columns?

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.


1 Answers

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),
        {},
    )
like image 71
Denis Otkidach Avatar answered Oct 18 '22 23:10

Denis Otkidach