LoginSignup
0
0

More than 1 year has passed since last update.

Tortoise ORMでモデルのプロパティをprintするための基本モデルの実装

Posted at

Tortoise ORMでモデルのプロパティをprintするための基本モデルの実装

Tortoise ORMはPythonで使用される軽量で柔軟なORMです。しかし、デフォルトではモデルのインスタンスをprintすると、ただのオブジェクトとして表示されるだけで、中身のプロパティは表示されません。この記事では、カスタム基本モデルを使用して、任意のモデルのプロパティを簡単に表示する方法を紹介します。

カスタム基本モデルの作成

まずは、カスタム基本モデルを定義しましょう。

from tortoise import fields
from tortoise.models import Model

class BaseModel(Model):
    class Meta:
        abstract = True
    def __repr__(self):
        field_values = ', '.join(f"{field}='{getattr(self, field)}'" for field in self._meta.fields_map.keys())
        return f"<{self.__class__.__name__}({field_values})>"
    def __str__(self):
        properties = ", ".join([f"{prop}={getattr(self, prop)}" for prop in self.__dict__ if not prop.startswith("_")])
        return f"{self.__class__.__name__}({properties})"

このカスタム基本モデルは、__repr____str__ メソッドをオーバーライドして、モデルのプロパティをprintする際にわかりやすい形式で表示されるようにしています。

簡単なモデル例の作成

次に、この基本モデルを継承して簡単なモデル例を作成しましょう。

from tortoise import fields

class User(BaseModel):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=50)
    email = fields.CharField(max_length=255)

    class Meta:
        table = "users"

使ってみる

user = User(id=1, username="john_doe", email="john.doe@example.com")
print(user)

# 出力:
# User(id=1, username='john_doe', email='john.doe@example.com')

List[User]のような場合でも表示できます。

users = [
    User(id=1, username="john_doe", email="john.doe@example.com"),
    User(id=2, username="jane_doe", email="jane.doe@example.com")
]
print(users)

# 出力:
# [<User(id='1', username='john_doe', email='john.doe@example.com')>, <User(id='2', username='jane_doe', email='jane.doe@example.com')>]

このように、カスタム基本モデルを作成して継承し、専用の関数を使用することで、Tortoise ORMのモデルのプロパティやリスト内のモデルプロパティをprintする際に、よりわかりやすい形式で表示されるようになります。これにより、デバッグやログ出力が容易になります。

コメント

PythonのORMといえばSQLAlchemyで、Tortoise ORMは少しマイナーになりますね。しかしTortoise ORMは非同期IOをサポートしパフォーマンス面での大きなメリットがあります。また、Aerichを使うことでデータベースのスキーマ変更を簡単かつ効率的に管理できます。とてもかっこいいモジュールなので、みなさんもぜひ活用されてみてはいかがでしょうか。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0