Instructions on how to leverage the CreateModelView in Django Ninja CRUD
CreateModelView
class CreateModelView(AbstractModelView)
A view class that handles creating instances of a model.
It allows customization through an model factory, pre- and post-save hooks,
and also supports decorators.
Example:
from ninja_crud import views, viewsets
from examples.models import Department, Employee
from examples.schemas import DepartmentIn, DepartmentOut, EmployeeIn, EmployeeOut
class DepartmentViewSet(viewsets.ModelViewSet):
model = Department
# Basic usage: Create a department
# POST /departments/
create_department_view = views.CreateModelView(
input_schema=DepartmentIn,
output_schema=DepartmentOut
)
# Advanced usage: Create an employee for a specific department
# POST /departments/{id}/employees/
create_employee_view = views.CreateModelView(
detail=True,
model_factory=lambda id: Employee(department_id=id),
input_schema=EmployeeIn,
output_schema=EmployeeOut,
)
__init__
def __init__(input_schema: Optional[Type[Schema]] = None,
output_schema: Optional[Type[Schema]] = None,
detail: bool = False,
model_factory: Union[DetailModelFactory, CollectionModelFactory,
None] = None,
pre_save: Union[CreateDetailSaveHook, CreateCollectionSaveHook,
None] = None,
post_save: Union[CreateDetailSaveHook, CreateCollectionSaveHook,
None] = None,
path: Optional[str] = None,
decorators: Optional[List[Callable]] = None,
router_kwargs: Optional[dict] = None) -> None
Initializes the CreateModelView.
Arguments:
-
input_schema
Optional[Type[Schema]], optional - The schema used to deserialize the payload.
Defaults to None. If not provided, thedefault_input_schema
of theModelViewSet
will be used. -
output_schema
Optional[Type[Schema]], optional - The schema used to serialize the created instance.
Defaults to None. If not provided, thedefault_output_schema
of theModelViewSet
will be used. -
detail
bool, optional - Whether the view is a detail or collection view. Defaults to False.If set to True,
model_factory
must be provided. -
model_factory
Union[DetailModelFactory, CollectionModelFactory, None], optional - A function
that returns a new instance of a model. Defaults to None.The function should have one of the following signatures:
- For
detail=False
: () -> Model - For
detail=True
: (id: Any) -> Model
If not provided, the
model
specified in theModelViewSet
will be used. - For
-
pre_save
Union[CreateDetailSaveHook, CreateCollectionSaveHook, None], optional - A function that
is called before saving the instance. Defaults to None.The function should have one of the following signatures:
- For
detail=False
: (request: HttpRequest, instance: Model) -> None - For
detail=True
: (request: HttpRequest, id: Any, instance: Model) -> None
If not provided, the function will be a no-op.
- For
-
post_save
Union[CreateDetailSaveHook, CreateCollectionSaveHook, None], optional - A function that
is called after saving the instance. Defaults to None.The function should have one of the following signatures:
- For
detail=False
: (request: HttpRequest, instance: Model) -> None - For
detail=True
: (request: HttpRequest, id: Any, instance: Model) -> None
If not provided, the function will be a no-op.
- For
-
path
Optional[str], optional - The path to use for the view. Defaults to:- For
detail=False
: "/" - For
detail=True
: "/{id}/{related_model_name_plural_to_snake_case}/"
Where
related_model_name_plural_to_snake_case
refers to the plural form of the related model's name,
converted to snake_case. For example, for a related model "ItemDetail", the path might look like
"/{id}/item_details/". This format is particularly useful when querying related entities or
sub-resources of a main resource. - For
-
decorators
Optional[List[Callable]], optional - A list of decorators to apply to the view. Defaults to []. -
router_kwargs
Optional[dict], optional - Additional arguments to pass to the router. Defaults to {}.
Overrides are allowed for most arguments except 'path', 'methods', and 'response'. If any of these
arguments are provided, a warning will be logged and the override will be ignored.
get_response
def get_response() -> dict
Provides a mapping of HTTP status codes to response schemas for the create view.
This response schema is used in API documentation to describe the response body for this view.
The response schema is critical and cannot be overridden using router_kwargs
. Any overrides
will be ignored.
Returns:
dict
- A mapping of HTTP status codes to response schemas for the create view.
Defaults to {201: self.output_schema}. For example, for a model "Department", the response
schema would be {201: DepartmentOut}.
get_operation_id
def get_operation_id(model_class: Type[Model]) -> str
Provides an operation ID for the create view.
This operation ID is used in API documentation to uniquely identify this view.
It can be overriden using the router_kwargs
.
Arguments:
model_class
Type[Model] - The Django model class associated with this view.
Returns:
str
- The operation ID for the create view. Defaults to:- For
detail=False
: "create_{model_name_to_snake_case}". For example, for a model "Department",
the operation ID would be "create_department". - For
detail=True
: "create{model_name_to_snake_case}{related_model_name_to_snake_case}". For
example, for a model "Department" and a related model "Item", the operation ID would be
"create_department_item".
- For
get_summary
def get_summary(model_class: Type[Model]) -> str
Provides a summary description for the create view.
This summary is used in API documentation to give a brief description of what this view does.
It can be overriden using the router_kwargs
.
Arguments:
model_class
Type[Model] - The Django model class associated with this view.
Returns:
str
- The summary description for the create view. Defaults to:- For
detail=False
: "Create {model_name}". For example, for a model "Department", the summary
would be "Create Department". - For
detail=True
: "Create {related_model_name} related to a {model_name}". For example, for a
model "Department" and a related model "Item", the summary would be "Create Item related to a
Department".
- For