tortoise / tortoise/tortoise-orm

How to translate MySQL code with two primary keys to Tortoise?

Open
#1,544 0 comments 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

I have this in my schema generation code:

--
-- Table structure for table `oc_location`
--

DROP TABLE IF EXISTS `oc_length_class_description`;
CREATE TABLE `oc_length_class_description` (
  `length_class_id` int(11) NOT NULL,
  `language_id` int(11) NOT NULL,
  `title` varchar(32) NOT NULL,
  `unit` varchar(4) NOT NULL,
  PRIMARY KEY (`length_class_id`,`language_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

How to rewrite this to Tortoise Model?
Like this?

class LengthClassDescription(Model):
    length_class_id = IntField(null=False, pk=True, validators=[MaxLengthValidator(11)])
    language_id = IntField(null=False, pk=True, validators=[MaxLengthValidator(11)])
    title = CharField(max_length=32, null=False)
    unit = CharField(max_length=4, null=False)

    class Meta:
        table = f"{database_prefix}length_class_description"

Or?

class LengthClassDescription(Model):
    length_class_id = IntField(null=False, validators=[MaxLengthValidator(11)])
    language_id = IntField(null=False, validators=[MaxLengthValidator(11)])
    title = CharField(max_length=32, null=False)
    unit = CharField(max_length=4, null=False)

    class Meta:
        table = f"{database_prefix}length_class_description"
        unique_together = (("length_class_id", "language_id"),)

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 with the two LengthClassDescription model definitions shown in the issue and check Tortoise ORM's documentation for composite primary keys and unique_together. Verify which declaration matches the MySQL schema's composite PRIMARY KEY and document the supported model definition and its schema-generation result.

Written by the indexing model from the issue text.

Assessment

Tech stack
mysql, python
Domain
databases
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.