Effortless & Tested CRUD Endpoints with Django Ninja.
Project description
Django Ninja CRUD
Django Ninja CRUD is an opinionated and powerful framework that accelerates the development of CRUD (Create, Read, Update, Delete) operations with Django Ninja, promoting best practices for efficient, robust endpoint creation. Equally significant is its integrated testing suite: a robust, user-friendly toolset ensuring that your endpoints are not only swiftly constructed but also meticulously tested and validated, reflecting a commitment to quality and reliability in your development workflow.
⚡️ Key Features
- Streamlined Setup: With just a few lines of code, your CRUD operations are ready to roll. No more copy-pasting or reinventing the wheel for each project.
- Focus on What Matters: Spend your precious time solving real problems, not stitching together basic operations. Django Ninja CRUD is like a trusty sidekick, handling the routine while you strategize the big picture.
- Reliable Code: Predefined blueprints are battle-tested and developer-approved. They're customizable, transparent, and designed with best practices in mind.
- Integrated Testing Framework: A robust, user-friendly toolset ensures that your endpoints are not only swiftly constructed but also meticulously tested and validated, reflecting a commitment to quality and reliability in your development workflow.
📝 Requirements
📈 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 with the router
DepartmentViewSet.register_routes(router)
# The router can then be used as normal
@router.get("/{name}", response=DepartmentOut)
def get_department_by_name(request: HttpRequest, name: str):
return Department.objects.get(name=name)
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.testing.core.components import PathParameters, Payloads
from ninja_crud.testing.views import (
CreateModelViewTest,
DeleteModelViewTest,
ListModelViewTest,
RetrieveModelViewTest,
UpdateModelViewTest,
)
from ninja_crud.testing.viewsets import ModelViewSetTestCase
from examples.models import Department
from examples.views.department_views import DepartmentViewSet
class TestDepartmentViewSet(ModelViewSetTestCase):
model_viewset_class = DepartmentViewSet
base_path = "api/departments"
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.department_1 = Department.objects.create(title="department-1")
cls.department_2 = Department.objects.create(title="department-2")
def get_path_parameters(self):
return PathParameters(ok={"id": self.department_1.id}, not_found={"id": 9999})
payloads = Payloads(
ok={"title": "department-3"},
bad_request={"wrong_field": "wrong_value"},
conflict={"title": "department-2"},
)
test_list_view = ListModelViewTest()
test_create_view = CreateModelViewTest(payloads=payloads)
test_retrieve_view = RetrieveModelViewTest(path_parameters=get_path_parameters)
test_update_view = UpdateModelViewTest(path_parameters=get_path_parameters, payloads=payloads)
test_delete_view = DeleteModelViewTest(path_parameters=get_path_parameters)
# You can then add additional tests as needed
def test_get_department_by_name(self):
response = self.client.get(f"{self.base_path}/department-1")
self.assertEqual(response.status_code, 200)
... # Additional assertions
With this package, these tests can be written in a consistent, straightforward way, making it easier to ensure your views are working as expected.
📚 Documentation
For more information, see the documentation.
[!NOTE]
With the launch of the
v0.4.0
release, we've made substantial enhancements to improve the developer experience while using this package. A myriad of new features has been introduced, and deep refactorings have taken place—primarily focusing on the testing suite.Currently, the documentation for the views has been thoroughly updated to reflect these changes. I'm in the process of updating and expanding the documentation for the revamped testing suite. Your patience and understanding are deeply valued as I work towards delivering a more detailed and up-to-date documentation experience. Thank you for supporting this project and its continuous growth!
🫶 Support
First and foremost, thank you for taking the time to explore this project. If you find it valuable or promising, please give it a star! Your recognition not only motivates but also helps others discover the project.
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. ✨
Your kindness and support make a world of difference. Thank you!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_ninja_crud-0.4.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | df465701eceb2cac13fe4cb20a97c27df9e109e57fdbf7a4eb591534b680fd04 |
|
MD5 | 9066cf290ea420670a0150f58bf0663d |
|
BLAKE2b-256 | 0a17c1a7f4a75c514d81bc21f492cdfdab9bfe862be986523f357262e992e652 |