tortoise / tortoise/tortoise-orm

Unable to create Model with custom PrimaryKey

Open
#1,262 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

Describe the bug
when creating a model, defining an attribute to be (pk=True) causes tortoise to throw the below error
tortoise.exceptions.ConfigurationError: Can't create model Post with two primary keys, only single primary key is supported
It seems to work fine if I explicitly define id as not being the PK
id=fields.SmallIntField(pk=False,required=False)
To Reproduce
Steps to reproduce the behavior, preferably a small code snippet.
Create a new model with a custom field as the primary key, but Do not explicitly define id:

class Post(BaseModel): id=fields.SmallIntField(pk=False,required=False) PostID = fields.SmallIntField(pk=True,unique=True) RawPost= fields.CharField(max_length=1600) Timestamp=fields.DatetimeField() Channel = fields.CharField(max_length=100) def __str__(self) -> str: return super(self.PostID).__str__()

Expected behavior
A clear and concise description of what you expected to happen.
Tortoise being smart enough to notice I'm defining a custom PK, without having to explicitly define id
Additional context
Add any other context about the problem here.
The Docs do not mention requiring to explicitly define id's pk as false.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the model definition in the issue, comparing the failing custom-primary-key case with the version that explicitly sets id=fields.SmallIntField(pk=False, required=False). Trace the model-field configuration that raises the two-primary-keys error; done means a custom primary key works without explicitly disabling the implicit id, with regression coverage for both cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.