0.2.2 • Published 2 years ago
prisma-client-py-tortoise-orm v0.2.2
prisma-client-py-tortoise-orm
this prisma client generator for Python Tortoise ORM
Getting Started
- Setup prisma
- Install
// use npm
npm install --save-dev prisma-client-py-tortoise-orm
// or yarn
yarn add -D prisma-client-py-tortoise-orm
- Add the generator to the schema
generator client {
provider = "prisma-client-py-tortoise-orm"
classNamePascalCase = true
valueNameSnakeCase = true
}
- Run generation
npx prisma generate
- check generated
Limitations
Since the prisma sdk only provides the information needed to build the client, Please don't use torroise orm to create table.
not support composite key
Not yet supported feature notes
- unsupported type field
- uuid
- model default cuid()
- model create/update helper
- Implicit m2m relationship
Generator options
modelsFile
type
: stringdefault
: 'models.py'desc
: generated file name
appName
type
: stringdefault
: 'models'desc
: tortoise orm app configexample
:# tortoise orm config config = { 'apps': { 'my_app': { # <- this name `my_app` 'models': ['__main__'], 'default_connection': 'default', } }, ...other
classNamePascalCase
type
: booleandefault
: truedesc
: DB model name convert to PascalCase for python naming style
valueNameSnakeCase
type
: booleandefault
: truedesc
: DB field name convert to SnakeCase for python naming style
createPyPackageInitFile
type
: booleandefault
: truedesc
: Generate folder automatically create __init__.py if it does not exist
sourceClassFile
type
: stringdefault
: "./prisma/base.py"desc
: The generated model will inherit the class of the same name asbase.py
.example
:
# ./db/base.py class User: class Meta: ordering = ['-id'] class PydanticMeta: exclude = ['password'] def updatePassword(self, passwd: str): self.password = hmac_sha256('secret_key', passwd)
# ./prisma/generated/model.py from db import base as base class User(base.User): id = field.IntField(pk=True) name = field.CharField(pk=True) class Meta(base.User.Meta): table = 'users' assert User.Meta.ordering assert User.PydanticMeta.exclude assert User.updatePassword
Generate example
schema.prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
generator client {
provider = "node ./dist/index.mjs"
output = "./generated"
}
/// model comment
model User {
/// field comment
id Int @id @default(autoincrement())
email String @unique
weight Float?
is18 Boolean?
name String?
wallet Decimal
successorId Int? @unique
successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])
predecessor User? @relation("BlogOwnerHistory")
role Role @default(USER)
posts Post[]
biography Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt @db.DateTime(0)
}
model Post {
id Int @id @default(autoincrement())
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
userId Int?
}
enum Role {
USER
ADMIN
}
models.py
import typing
from enum import Enum
from tortoise import fields
from tortoise.models import Model
class Role(str,Enum):
'''
- USER
- ADMIN
'''
USER = 'USER'
ADMIN = 'ADMIN'
class User(Model):
'''
model comment
fields:
- 🔟 id [Int] 🔑
- default: auto_increment()
- doc: field comment
- 🆎 *email [String] 📌
- 🔟 weight [Float?]
- ✅ is18 [Boolean?]
- 🆎 name [String?]
- 🔟 *wallet [Decimal]
- 🪢 successor [User?]
- 🪢 predecessor [User?]
- 🪢 role [Role]
- default: Role.USER
- 🪢 posts [Post]
- 🪢 *biography [Json]
- 🕑 createdAt [DateTime]
- default: now()
- 🕑 *updatedAt [DateTime]
'''
id = fields.IntField(pk=True, description='field comment')
email = fields.CharField(max_length=255, unique=True)
weight = fields.FloatField(null=True)
is_18 = fields.BooleanField(null=True)
name = fields.CharField(max_length=255, null=True)
wallet = fields.DecimalField(max_digits=12, decimal_places=2)
successor: fields.OneToOneRelation[typing.Union['User', typing.Any]] = fields.OneToOneField(source_field='successorId', model_name='models.User', to_field='id', related_name='user_successor', null=True)
predecessor: fields.ReverseRelation['User']
role = fields.CharEnumField(enum_type=Role, default=Role.USER)
posts: fields.ReverseRelation['Post']
biography = fields.JSONField()
created_at = fields.DatetimeField(auto_now_add=True)
updated_at = fields.DatetimeField(auto_now=True)
class Meta:
table = 'User'
def __str__(self) -> str:
return f'User<{self.id}>'
class Post(Model):
'''
fields:
- 🔟 id [Int] 🔑
- default: auto_increment()
- 🪢 user [User?]
'''
id = fields.IntField(pk=True)
user: fields.ForeignKeyRelation[typing.Union['User', typing.Any]] = fields.ForeignKeyField(source_field='userId', model_name='models.User', to_field='id', related_name='post_user', on_delete=fields.SET_NULL, null=True)
class Meta:
table = 'Post'
def __str__(self) -> str:
return f'Post<{self.id}>'
__all__ = ['Role', 'User', 'Post']