django-ninja-aio-crudのロゴ

django-ninja-aio-crud

コミュニティ
caspel26

Async dynamic CRUD framework for Django Ninja — built-in auth, filtering, pagination, automatic serialization, and MCP tools for AI agents.

公開者caspel26
リポジトリdjango-ninja-aio-crud
言語Python
フォーク
1
スター
51
利用可能なツール
0
通信方式stdio
カテゴリ
ライセンスMIT
リンク
  • ツールをAIワークフローに接続

    django-ninja-aio-crudは、対応するAIクライアントやAIエージェントから利用できるMCP機能を提供します。

  • 利用可能なツール(0個)

    呼び出し可能なアクションを以下で確認できます。サーバーから提供されている場合は、名前や説明も表示されます。

  • コピーして使える設定

    セットアップ用の設定例を使って、お好みのMCPクライアントにこのサーバーを設定できます。

  • オープンソースプロジェクトの注目度

    リンク先のリポジトリには51件のスターと1件のフォークがあります。


Features

FeatureDescription
🔒 Type SafetyGeneric classesFull IDE autocomplete and type checking with generic ModelUtil, Serializer, and APIViewSet
Meta-driven SerializerDynamic schemasGenerate CRUD schemas for existing Django models without changing base classes
Async CRUD ViewSetsFull operationsCreate, list, retrieve, update, delete — all async
Auto SchemasPydantic generationAutomatic read/create/update schemas from ModelSerializer
Dynamic Query ParamsRuntime schemasBuilt with pydantic.create_model for flexible filtering
Per-method AuthGranular controlauth, get_auth, post_auth, etc.
Async PaginationCustomizablePageNumberPagination, CursorPagination, or custom — DB-level slicing
M2M RelationsAdd/remove/listEndpoints via M2MRelationSchema with filtering support
Reverse RelationsNested serializationAutomatic handling of reverse FK and M2M
Nested WritesAtomic creationCreate a parent and owned reverse-FK children in one request
Auto Admin RelationsInlines and widgetsGenerate FK/O2O inlines and standard M2M dual-list widgets
Bulk OperationsCreate/update/deleteOpt-in bulk endpoints with partial success semantics and configurable response fields
Custom Actions@action decoratorDetail and list actions with auth inheritance, custom decorators, and auto URL generation
Lifecycle HooksExtensiblebefore_save, after_save, custom_actions, on_delete, and more
Schema ValidatorsPydantic validators@field_validator and @model_validator on serializer classes
ORJSON RendererPerformanceBuilt-in fast JSON rendering via NinjaAIO
AI Agent IntegrationMCP toolsExpose ViewSets as MCP tools for any MCP client

See It In Action


Quick Start

Option A: Meta-driven Serializer (existing models)

Use this if you already have Django models and don't want to change their base class.

python
from ninja_aio.models import serializers
from ninja_aio.views import APIViewSet
from ninja_aio import NinjaAIO
from . import models

class BookSerializer(serializers.Serializer):
    class Meta:
        model = models.Book
        schema_in = serializers.SchemaModelConfig(fields=["title", "published"])
        schema_out = serializers.SchemaModelConfig(fields=["id", "title", "published"])
        schema_update = serializers.SchemaModelConfig(
            optionals=[("title", str), ("published", bool)]
        )

api = NinjaAIO()

@api.viewset(models.Book)
class BookViewSet(APIViewSet):
    serializer_class = BookSerializer

Option B: ModelSerializer (new projects)

Define models with built-in serialization for minimal boilerplate.

models.py

python
from django.db import models
from ninja_aio.models import ModelSerializer

class Book(ModelSerializer):
    title = models.CharField(max_length=120)
    published = models.BooleanField(default=True)

    class ReadSerializer:
        fields = ["id", "title", "published"]

    class CreateSerializer:
        fields = ["title", "published"]

    class UpdateSerializer:
        optionals = [("title", str), ("published", bool)]

views.py

python
from ninja_aio import NinjaAIO
from ninja_aio.views import APIViewSet
from .models import Book

api = NinjaAIO()

@api.viewset(Book)
class BookViewSet(APIViewSet):
    pass

Visit /docs — CRUD endpoints ready.


Query Filtering

python
@api.viewset(Book)
class BookViewSet(APIViewSet):
    query_params = {"published": (bool, None), "title": (str, None)}

    async def query_params_handler(self, queryset, filters):
        if filters.get("published") is not None:
            queryset = queryset.filter(published=filters["published"])
        if filters.get("title"):
            queryset = queryset.filter(title__icontains=filters["title"])
        return queryset
GET /book/?published=true&title=python

Many-to-Many Relations

python
from ninja_aio.schemas import M2MRelationSchema

class Tag(ModelSerializer):
    name = models.CharField(max_length=50)
    class ReadSerializer:
        fields = ["id", "name"]

class Article(ModelSerializer):
    title = models.CharField(max_length=120)
    tags = models.ManyToManyField(Tag, related_name="articles")
    class ReadSerializer:
        fields = ["id", "title", "tags"]

@api.viewset(Article)
class ArticleViewSet(APIViewSet):
    m2m_relations = [
        M2MRelationSchema(
            model=Tag,
            related_name="tags",
            filters={"name": (str, "")}
        )
    ]

    async def tags_query_params_handler(self, queryset, filters):
        n = filters.get("name")
        if n:
            queryset = queryset.filter(name__icontains=n)
        return queryset

Endpoints:

GET  /article/{pk}/tag?name=dev
POST /article/{pk}/tag/    body: {"add": [1, 2], "remove": [3]}

Nested Creation

Declare owned child relations on the parent's create config:

python
class Order(ModelSerializer):
    name = models.CharField(max_length=120)

    class CreateSerializer:
        fields = ["name"]
        nested = {"items": OrderItem}

OrderItem must be a ModelSerializer with a foreign key to Order and related_name="items". Its parent FK is excluded from the nested input and injected automatically. One request creates the order and its items, rolling back the whole graph if a child fails. Nested writes are currently create-only.

See Nested Writes and Auto Admin Relations.


Authentication (JWT)

python
from ninja_aio.auth import AsyncJwtBearer
from joserfc import jwk

class JWTAuth(AsyncJwtBearer):
    jwt_public = jwk.RSAKey.import_key("-----BEGIN PUBLIC KEY----- ...")
    jwt_alg = "RS256"
    claims = {"sub": {"essential": True}}

    async def auth_handler(self, request):
        book_id = self.dcd.claims.get("sub")
        return await Book.objects.aget(id=book_id)

@api.viewset(Book)
class SecureBookViewSet(APIViewSet):
    auth = [JWTAuth()]
    get_auth = None  # list/retrieve remain public

Lifecycle Hooks

Available on every save/delete cycle:

HookWhen
on_create_before_saveBefore first save
on_create_after_saveAfter first save
before_saveBefore any save
after_saveAfter any save
on_deleteAfter deletion
custom_actions(payload)Create/update custom field logic
post_create()After create commit

Custom Endpoints

Option A: @action Decorator (recommended)

python
from ninja import Schema, Status
from ninja_aio.decorators import action

class StatsSchema(Schema):
    total: int

@api.viewset(Book)
class BookViewSet(APIViewSet):
    @action(detail=False, methods=["get"], url_path="stats", response=StatsSchema)
    async def stats(self, request):
        total = await Book.objects.acount()
        return {"total": total}

    @action(detail=True, methods=["post"], url_path="publish")
    async def publish(self, request, pk):
        book = await self.model_util.get_object(request, pk)
        book.published = True
        await book.asave()
        return Status(200, {"message": "published"})
GET  /book/stats/       → {"total": 42}
POST /book/{pk}/publish/ → {"message": "published"}

Option B: operations Decorators

python
from ninja_aio.decorators import api_get

@api.viewset(Book)
class BookViewSet(APIViewSet):
    @api_get("/stats/")
    async def stats(self, request):
        total = await Book.objects.acount()
        return {"total": total}

AI Agent Integration (MCP)

Expose every registered APIViewSet — CRUD, bulk operations, and custom @action/@on endpoints — as well as any custom APIView, as MCP tools any MCP client can call directly.

sh
pip install "django-ninja-aio-crud[mcp]"

Option A: manage.py mcp_server (recommended)

Add "ninja_aio" to INSTALLED_APPS to pick up the bundled management command:

python
INSTALLED_APPS = [
    ...,
    "ninja_aio",
]
sh
python manage.py mcp_server myproject.api.api

Or set a default so you can drop the argument:

python
# settings.py
NINJA_AIO_MCP_API = "myproject.api.api"
json
{
  "mcpServers": {
    "myproject": {
      "type": "stdio",
      "command": "python",
      "args": ["manage.py", "mcp_server"]
    }
  }
}

Option B: standalone script

python
# mcp_server.py
import asyncio
import django
django.setup()

from myproject.api import api  # your NinjaAIO() instance with @api.viewset(...) registered
from ninja_aio.mcp import run_mcp_server

if __name__ == "__main__":
    asyncio.run(run_mcp_server(api))
json
{
  "mcpServers": {
    "myproject": {
      "type": "stdio",
      "command": "python",
      "args": ["mcp_server.py"]
    }
  }
}

Every @api.viewset(...)-registered ViewSet and @api.view(...)-registered View is picked up automatically (or pass viewsets=[...]/views=[...] explicitly). Tools are named <model>_<operation> for ViewSets — e.g. book_create, book_list, book_retrieve, book_update, book_delete, book_bulk_create, book_publish — and <viewclass>_<function>_<method> for plain Views — e.g. bookview_stats_get.

⚠️ Auth caveat: tool calls invoke the same registered view logic as HTTP requests (filters, pagination, and on_before_operation/on_before_object_operation/query_params_handler hooks all run identically) but bypass django-ninja's auth= wiring, since that applies at the router layer, not inside the handler. Pass request_factory to attach your own request.user/auth context, and use viewset hooks to enforce authorization for MCP-driven calls:

python
from ninja_aio.mcp import NinjaAIOMCPServer

def mcp_request_factory():
    from django.test.client import AsyncRequestFactory
    request = AsyncRequestFactory().get("/mcp/")
    request.user = get_service_account_user()  # your own resolution logic
    return request

server = NinjaAIOMCPServer(api, request_factory=mcp_request_factory)

Bulk Operations

python
@api.viewset(Book)
class BookViewSet(APIViewSet):
    bulk_operations = ["create", "update", "delete"]
    bulk_response_fields = "title"  # Optional: return titles instead of PKs
POST   /book/bulk/  body: [{...}, {...}]         → {"success": {"count": 2, "details": ["Book 1", "Book 2"]}}
PATCH  /book/bulk/  body: [{id, ...}, {id, ...}] → {"success": {"count": 2, "details": ["Updated 1", "Updated 2"]}}
DELETE /book/bulk/  body: {"ids": [1, 2]}         → {"success": {"count": 2, "details": ["Book 1", "Book 2"]}}

Pagination

Default: PageNumberPagination. Override per ViewSet:

python
from ninja.pagination import PageNumberPagination, CursorPagination

class LargePagination(PageNumberPagination):
    page_size = 50
    max_page_size = 200

@api.viewset(Book)
class BookViewSet(APIViewSet):
    pagination_class = LargePagination
    # Or use cursor-based pagination for large datasets:
    # pagination_class = CursorPagination

Schema Validators

Add Pydantic @field_validator and @model_validator directly on serializer classes for input validation.

ModelSerializer

Declare validators on inner serializer classes:

python
from django.db import models
from pydantic import field_validator, model_validator
from ninja_aio.models import ModelSerializer

class Book(ModelSerializer):
    title = models.CharField(max_length=120)
    description = models.TextField(blank=True)

    class CreateSerializer:
        fields = ["title", "description"]

        @field_validator("title")
        @classmethod
        def validate_title_min_length(cls, v):
            if len(v) < 3:
                raise ValueError("Title must be at least 3 characters")
            return v

    class UpdateSerializer:
        optionals = [("title", str), ("description", str)]

        @field_validator("title")
        @classmethod
        def validate_title_not_empty(cls, v):
            if v is not None and len(v.strip()) == 0:
                raise ValueError("Title cannot be blank")
            return v

    class ReadSerializer:
        fields = ["id", "title", "description"]

        @model_validator(mode="after")
        def enrich_output(self):
            # Transform or enrich the output schema
            return self

Meta-driven Serializer

Use dedicated {Type}Validators inner classes:

python
from pydantic import field_validator, model_validator
from ninja_aio.models import serializers
from . import models

class BookSerializer(serializers.Serializer):
    class Meta:
        model = models.Book
        schema_in = serializers.SchemaModelConfig(fields=["title", "description"])
        schema_out = serializers.SchemaModelConfig(fields=["id", "title", "description"])
        schema_update = serializers.SchemaModelConfig(
            optionals=[("title", str), ("description", str)]
        )

    class CreateValidators:
        @field_validator("title")
        @classmethod
        def validate_title_min_length(cls, v):
            if len(v) < 3:
                raise ValueError("Title must be at least 3 characters")
            return v

    class UpdateValidators:
        @field_validator("title")
        @classmethod
        def validate_title_not_empty(cls, v):
            if v is not None and len(v.strip()) == 0:
                raise ValueError("Title cannot be blank")
            return v

    class ReadValidators:
        @model_validator(mode="after")
        def enrich_output(self):
            return self

Validator class mapping:

Schema typeModelSerializerSerializer (Meta-driven)
CreateCreateSerializerCreateValidators
UpdateUpdateSerializerUpdateValidators
ReadReadSerializerReadValidators
DetailDetailSerializerDetailValidators

Disable Operations

python
@api.viewset(Book)
class ReadOnlyBookViewSet(APIViewSet):
    disable = ["update", "delete"]

Framework Comparison

How does Django Ninja AIO compare to other Python REST frameworks? We benchmark against Django Ninja, ADRF, and FastAPI — focusing on complex async operations like reverse FK and M2M serialization.

FrameworkLines of CodeReverse FK HandlingAuto PrefetchCRUD Automation
Django Ninja AIO~20AutomaticYesFull
FastAPI~80+Manual async iterationNoNone
ADRF~45+Needs serializer configManualPartial

View Full Comparison — Code examples, benchmark results, and interactive charts


Performance

View live benchmarks tracking schema generation, serialization, and CRUD throughput:

Live Performance Report — Interactive charts with historical trends

Performance Tips

  • Use queryset_request classmethod to select_related / prefetch_related
  • Index frequently filtered fields
  • Keep pagination enabled for large datasets
  • Limit slices (queryset = queryset[:1000]) for heavy searches

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for your changes
  4. Run lint: ruff check .
  5. Open a Pull Request

Support

If you find this project useful, consider giving it a star or supporting development:


License

MIT License. See LICENSE.

インストール

TypingMind
{
  "mcpServers": {
    "django-ninja-aio-crud": {
      "command": "python",
      "args": [
        "manage.py",
        "mcp_server"
      ]
    }
  }
}

django-ninja-aio-crudのMCPを複数のAIモデルで活用

TypingMindはワークスペース単位でMCPツールに接続します。そのため、一度django-ninja-aio-crudに接続すれば、モデルごとに個別に設定することなく、TypingMind内のさまざまなAIモデルで利用できます。 このMCPは、デバイス上のTypingMind MCPコネクタを通じてローカルで動作します。

ローカルコネクタのセットアップガイド

MCPサーバーが、お使いのコンピューター上のローカルファイル、アプリ、非公開リソースにアクセスする必要がある場合は、この方法を使います。

1

MCP設定を開く

TypingMindで「設定」→「詳細設定」→「Model Context Protocol」の順に進み、「コネクタを設定」を選択してください。

  1. ブラウザでTypingMindを開いてください。
  2. 設定アイコンをクリックしてください。
  3. 「詳細設定」に移動してください。
  4. 「Model Context Protocol」セクションを開いてください。
  5. 「コネクタを設定」をクリックし、「このデバイス」を選択してください。
「このデバイス」が選択されたTypingMindのMCPコネクタ設定画面
2

コネクタのコマンドを実行

「このデバイス」を選択し、TypingMindからコマンドをコピーしてターミナルで実行してください。MCPの使用中は、プロセスを実行したままにしてください。

  1. TypingMindに表示されるセットアップコマンドをコピーしてください。
  2. macOSではターミナルを、WindowsではWindows Terminalを開いてください。
  3. コマンドを貼り付けて実行してください。
  4. ターミナルで続行の確認を求められた場合は、パッケージのインストールを承認してください。
  5. MCPツールの使用中は、ターミナルウィンドウを開いたまま、プロセスの実行を継続してください。
3

django-ninja-aio-crudをサーバーとして追加

コネクタのステータスが「準備完了」になったら、「サーバーを編集」をクリックし、MCPサーバーの設定を貼り付けてください。

  1. コネクタのステータスが「準備完了」になるまでお待ちください。
  2. 「サーバーを編集」をクリックしてください。
  3. django-ninja-aio-crudのMCPサーバー設定を貼り付けてください。
  4. サーバー一覧を保存してください。
  5. コネクタのステータスが「準備完了」のままか確認するには、画面を更新してください。
稼働中のサーバーと「サーバーを編集」ボタンが表示されたTypingMindのMCP設定画面
{
  "mcpServers": {
    "django-ninja-aio-crud": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

複数のモデルで同じ接続を使用

サーバー一覧を保存し、「プラグイン」を開いてdjango-ninja-aio-crudのMCPツールを有効にしてください。その後、TypingMindで対応するAIモデルを選択し、チャットでツールを使うか、AIエージェントに割り当ててください。

  1. TypingMindの「プラグイン」ページを開いてください。
  2. django-ninja-aio-crudのMCPツールを有効にしてください。
  3. チャットを開始し、使用するAIモデルを選択してください。
  4. MCPツールをチャットで使うか、AIエージェントに割り当ててください。
  5. MCPに再接続することなく、必要に応じて別のAIモデルに切り替えられます。
選択したAIモデルと有効なMCPツールを使用したTypingMindのチャット
django-ninja-aio-crudを使ってこのタスクを手伝ってもらえますか?
django-ninja-aio-crud
はい、読みました。
django-ninja-aio-crudで調べた結果をお伝えします。

よくある質問

django-ninja-aio-crud MCPサーバーは何に使いますか?

django-ninja-aio-crudは、対応するAIクライアントを外部ツールやコンテキストに接続するためのMCPサーバーです。TypingMindでは、このMCPサーバーを一度追加するだけで、AIワークスペース内でそのツールを利用できるようになります。

TypingMindでは、複数のAIモデルでdjango-ninja-aio-crud MCPを利用できますか?

はい。TypingMindはワークスペース単位でMCPツールに接続するため、モデルごとにMCPサーバーを設定する必要はありません。Claude、ChatGPT、Geminiや、TypingMindで設定したその他のAIモデルでdjango-ninja-aio-crudを利用できます。

TypingMindでdjango-ninja-aio-crud MCPを使うメリットは何ですか?

TypingMindは、複数のAIモデル、プロンプト、プラグイン、AIエージェント、APIキー、MCPツールを1つのワークスペースにまとめられる、LLMチャット向けのトップクラスのフロントエンドです。django-ninja-aio-crudを接続すると、TypingMindでチャットのワークフローを整理しながら、お好みのモデルでそのMCPツールを利用できます。

django-ninja-aio-crud MCPをTypingMindに接続するにはどうすればよいですか?

django-ninja-aio-crudはTypingMindのローカルMCPコネクタ経由で動作します。MCPサーバーがコンピューター上のローカルファイル、デスクトップアプリ、コマンドラインツール、プライベートリソースにアクセスする必要がある場合に最適です。

TypingMindでdjango-ninja-aio-crud MCPのどのようなツールを利用できますか?

django-ninja-aio-crudはMCP機能を提供しています。TypingMindのプラグインページで有効にすると、チャットで使用したり、AIエージェントに割り当てたりできます。

django-ninja-aio-crud MCPを使うには、APIキーをTypingMindと共有する必要がありますか?

いいえ。TypingMindはローカルファーストの設計で、モデルプロバイダー、APIキー、プロンプト、MCP設定をご自身で管理できます。django-ninja-aio-crudで認証が必要な場合は、接続の作成時に、そのMCPサーバーに必要なヘッダー、OAuth設定、またはローカル設定を追加してください。

関連するMCPサーバー

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇