https://github.com/hbakri/django-ninja-crud Skip to content Toggle navigation Sign in * Product + Actions Automate any workflow + Packages Host and manage packages + Security Find and fix vulnerabilities + Codespaces Instant dev environments + Copilot Write better code with AI + Code review Manage code changes + Issues Plan and track work + Discussions Collaborate outside of code Explore + All features + Documentation + GitHub Skills + Blog * Solutions For + Enterprise + Teams + Startups + Education By Solution + CI/CD & Automation + DevOps + DevSecOps Resources + Learning Pathways + White papers, Ebooks, Webinars + Customer Stories + Partners * Open Source + GitHub Sponsors Fund open source developers + The ReadME Project GitHub community articles Repositories + Topics + Trending + Collections * Pricing Search or jump to... Search code, repositories, users, issues, pull requests... Search [ ] Clear Search syntax tips Provide feedback We read every piece of feedback, and take your input very seriously. [ ] [ ] Include my email address so I can be contacted Cancel Submit feedback Saved searches Use saved searches to filter your results more quickly Name [ ] Query [ ] To see all available qualifiers, see our documentation. Cancel Create saved search Sign in Sign up You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} hbakri / django-ninja-crud Public * * Notifications * Fork 5 * Star 104 Declarative CRUD Endpoints & Tests with Django Ninja. django-ninja-crud.readme.io License MIT license 104 stars 5 forks Activity Star Notifications * Code * Issues 6 * Pull requests 0 * Discussions * Actions * Projects 1 * Security * Insights Additional navigation options * Code * Issues * Pull requests * Discussions * Actions * Projects * Security * Insights hbakri/django-ninja-crud This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. main Switch branches/tags [ ] Branches Tags Could not load branches Nothing to show {{ refName }} default View all branches Could not load tags Nothing to show {{ refName }} default View all tags Name already in use A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch? Cancel Create 1 branch 11 tags Code * Local * Codespaces * Clone HTTPS GitHub CLI [https://github.com/h] Use Git or checkout with SVN using the web URL. [gh repo clone hbakri] Work fast with our official CLI. Learn more about the CLI. * Open with GitHub Desktop * Download ZIP Sign In Required Please sign in to use Codespaces. Launching GitHub Desktop If nothing happens, download GitHub Desktop and try again. Launching GitHub Desktop If nothing happens, download GitHub Desktop and try again. Launching Xcode If nothing happens, download Xcode and try again. Launching Visual Studio Code Your codespace will open once ready. There was a problem preparing your codespace, please try again. Latest commit Git stats * 178 commits Files Permalink Failed to load latest commit information. Type Name Latest commit message Commit time .github feat: add support for Django v5.0 (#346) December 9, 2023 15:53 docs feat: add support for Django v5.0 (#346) December 9, 2023 15:53 examples docs: update README.md (#333) November 29, 2023 18:18 ninja_crud docs: remove super().setUpTestData() calls in examples (#341) November 30, 2023 13:44 tests refactor: [?][?] refactor handle_request to AbstractModelViewTest (#328) November 26, 2023 17:58 .gitignore docs: document testing's core components (#305) November 16, 2023 19:29 .pre-commit-config.yaml chore: [?] remove default_language_version in pre-commit (#295) November 10, 2023 16:25 CONTRIBUTING.md docs: update CONTRIBUTION.md (#219) September 4, 2023 14:23 LICENSE.md chore: rename LICENSE file to LICENSE.md (#104) July 30, 2023 15:27 README.md docs: update README.md (#349) December 13, 2023 23:59 pyproject.toml feat: add support for Django v5.0 (#346) December 9, 2023 15:53 View code [ ] Django Ninja CRUD Featured Article Key Features Requirements [?][?] Installation Example Usage Testing Documentation Support README.md Django Ninja CRUD Tests Coverage PyPI version Downloads License Ruff Django Ninja CRUD Django Ninja CRUD is a powerful, declarative, and yet opinionated framework that simplifies the development of CRUD (Create, Read, U pdate, Delete) endpoints and tests with Django Ninja. It promotes best practices for efficient, robust endpoint creation, allowing you to focus on what matters most: solving real problems. Initially inspired by DRF's ModelViewSet, Django Ninja CRUD evolved to address its limitations, adopting a composition-over-inheritance approach to achieve true modularity - a foundational step towards a broader declarative interface for endpoint creation. Featured Article I'm excited to share my recent article: "Introducing Django Ninja CRUD" on Medium. This piece dives into the journey of creating Django Ninja CRUD, detailing its features, benefits, and the paradigm shift it brings to Django development. Key Features * Purely Declarative: Embrace an approach where defining views and tests is a matter of declaring what you want, not how to achieve it. * Unmatched Modularity: Tailor your viewsets with the desired CRUD views and customize each view's behavior with ease. Extend the flexibility by creating your own subclasses of the provided views and tests. * Powerful Testing Framework: Leverage a matrix-based testing framework for defining diverse test scenarios declaratively. * Focus on What Matters: Spend more time solving real-world problems and less on CRUD boilerplate. Its blend of declarative syntax, modularity, and powerful testing capabilities sets a new standard for developers seeking efficiency and precision. Django Ninja CRUD is not just a tool; it's a paradigm shift in Django web application development and testing. Requirements Python versions Django versions Django Ninja versions [?][?] Installation pip install django-ninja-crud For more information, see the installation guide. Example Usage Let's imagine you're building a system for a university and you have a model called Department. Each department in your university has a unique title. # examples/models.py from django.db import models class Department(models.Model): title = models.CharField(max_length=255, unique=True) To interact with this data, we need a way to convert it between Python objects and a format that's easy to read and write (like JSON). In Django Ninja, we do this with Schema: # examples/schemas.py from ninja import Schema class DepartmentIn(Schema): title: str class DepartmentOut(Schema): id: int title: str The DepartmentIn schema defines what data we need when creating or updating a department. The DepartmentOut schema defines what data we'll provide when retrieving a department. Now, here comes the power of Django Ninja CRUD. With it, you can set up the CRUD operations for the Department model with just a few lines of code: # examples/views/department_views.py from django.http import HttpRequest from ninja import Router from ninja_crud import views, viewsets from examples.models import Department from examples.schemas import DepartmentIn, DepartmentOut router = Router() class DepartmentViewSet(viewsets.ModelViewSet): model = Department default_input_schema = DepartmentIn default_output_schema = DepartmentOut list_view = views.ListModelView() create_view = views.CreateModelView() retrieve_view = views.RetrieveModelView() update_view = views.UpdateModelView() delete_view = views.DeleteModelView() # The register_routes method must be called to register the routes DepartmentViewSet.register_routes(router) # Beyond the CRUD operations managed by the viewset, # the router can be used in the standard Django Ninja way @router.get("/statistics/", response=dict) def retrieve_department_statistics(request: HttpRequest): return {"total": Department.objects.count()} Testing A key advantage of this package is that it makes your views easy to test. Once you've set up your CRUD operations, you can write tests to ensure they're working as expected. Here's an example of how you might test the Department operations: # examples/tests/test_department_views.py from ninja_crud import testing from examples.models import Department from examples.views.department_views import DepartmentViewSet class TestDepartmentViewSet(testing.viewsets.ModelViewSetTestCase): model_viewset_class = DepartmentViewSet base_path = "api/departments" @classmethod def setUpTestData(cls): cls.department_1 = Department.objects.create(title="department-1") cls.department_2 = Department.objects.create(title="department-2") @property def path_parameters(self): return testing.components.PathParameters( ok={"id": self.department_1.id}, not_found={"id": 9999} ) @property def payloads(self): return testing.components.Payloads( ok={"title": "department-3"}, bad_request={}, conflict={"title": self.department_2.title}, ) test_list_view = testing.views.ListModelViewTest() test_create_view = testing.views.CreateModelViewTest(payloads) test_retrieve_view = testing.views.RetrieveModelViewTest(path_parameters) test_update_view = testing.views.UpdateModelViewTest(path_parameters, payloads) test_delete_view = testing.views.DeleteModelViewTest(path_parameters) # You can then add additional tests as needed def test_retrieve_department_statistics(self): response = self.client.get(f"{self.base_path}/statistics/") self.assertEqual(response.status_code, 200) ... # Additional assertions Documentation For more information, see the documentation. Support First and foremost, a heartfelt thank you for taking an interest in this project. If it has been helpful to you or you believe in its potential, kindly consider giving it a star on GitHub. Such recognition not only fuels my drive to maintain and improve this work but also makes it more visible to new potential users and contributors. GitHub Repo stars If you've benefited from this project or appreciate the dedication behind it, consider showing further support. Whether it's the price of a coffee, a word of encouragement, or a sponsorship, every gesture adds fuel to the open-source fire, making it shine even brighter. Sponsor Buy me a coffee Your kindness and support make a world of difference. Thank you! About Declarative CRUD Endpoints & Tests with Django Ninja. django-ninja-crud.readme.io Topics python django django-ninja django-ninja-crud Resources Readme License MIT license Activity Stars 104 stars Watchers 2 watching Forks 5 forks Report repository Releases 10 v0.4.1 Latest Nov 29, 2023 + 9 releases Sponsor this project Sponsor Learn more about GitHub Sponsors Contributors 4 * @hbakri hbakri Hicham Bakri * @lucasrcezimbra lucasrcezimbra Lucas Rangel Cezimbra * @kuramen kuramen cbrunie * @chengfangho chengfangho Languages * Python 100.0% Footer (c) 2023 GitHub, Inc. Footer navigation * Terms * Privacy * Security * Status * Docs * Contact * You can't perform that action at this time.