How to implement a composite primary key #1244
-
First Check
Commit to Help
Example Codeclass test(SQLModel, table=True):
src_ppn: str = Field(primary_key=True)
dst_ppn: str = Field(primary_key=True)
__table_args__ = (
PrimaryKeyConstraint(src_ppn, dst_ppn),
) DescriptionI want to create a table containing a composite primary key ArgumentError: String column name or column expression for DDL constraint expected, got FieldInfo(annotation=NoneType, required=True). Operating SystemLinux Operating System DetailsUbuntu 22.04 SQLModel Version0.0.22 Python Version3.9.7 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I guess there's something wrong with |
Beta Was this translation helpful? Give feedback.
-
You don't actually need from sqlalchemy import PrimaryKeyConstraint
from sqlmodel import SQLModel, Field, create_engine
class test(SQLModel, table=True):
src_ppn: str = Field(primary_key=True)
dst_ppn: str = Field(primary_key=True)
__table_args__ = (PrimaryKeyConstraint("src_ppn", "dst_ppn"),)
class test2(SQLModel, table=True):
src_ppn: str = Field(primary_key=True)
dst_ppn: str = Field(primary_key=True)
engine = create_engine("sqlite:///", echo=True)
SQLModel.metadata.create_all(engine) Output (as you can see there is no difference):
|
Beta Was this translation helpful? Give feedback.
You don't actually need
PrimaryKeyConstraint
.Just specifying
primary_key=True
for both fields is enough to create composite primary key:Output (as you can see there is no difference):