Django_APIView
Implement a base generic view for handling model RESTful endpoints
Usage
from django.db import models
from django_modelapiview import JSONMixin
class MyModel(JSONMixin, models.Model):
"""
Declare your model as you usually do but
add a json_fields list
"""
json_fields:list[str] = ['text', 'image', 'fk', 'fk_reverse', 'm2m', 'my_method']
text = models.TextField()
image = models.ImageField()
fk = models.ForeignKey(...)
m2m = models.ManyToManyField(...)
def my_method(self):
return "my custom value"
from django_modelapiview import APIView
from django_modelapiview.responses import APIResponse
from .models import MyModel
class MyView(APIView):
route:str = "myroute"
enforce_authentification:bool = True
def get(self, request, *args, **kwargs) -> APIResponse:...
from django_modelapiview import ModelAPIView
from .models import MyModel
class MyModelView(ModelAPIView):
model:JSONMixin = MyModel
route:str = "mymodels"
queryset:QuerySet = MyModel.objects.all()
singular_name:str = "my model"
plural_name:str = "my models"
enforce_authentification:bool = True
query_parameters:list[tuple[str, Callable[[QuerySet, object], QuerySet]]] = [
('order_by', lambda queryset, field_names: queryset.order_by(*field_names.split(",")) if field_names else queryset),
('limit', lambda queryset, limit: queryset[:int(limit)] if limit else queryset),
]
def get(self, request, *args, **kwargs) -> APIResponse:...
from django.urls import path, include
from . import views
urlpatterns = [
path("", include("django_routeview")),
]
https://myhost.com/api/mymodel/?order_by=-id&limit=1
https://myhost.com/api/mymodel/?id__in=1,2,3&foreignkey__id__in=2,3&field__lte=5
https://myhost.com/api/mymodel/?manytomany__in=2,3&field__lte=5&limit=10
It also supports translation:
First enable it as an app
INSTALLED_APPS = [
...
'django_modelapiview',
...
]
Then change the language using GET parameters:
https://myhost.com/api/mymodel/?lang=fr
Using base views
Django ModelAPIView provides 2 base views:
- LoginView: to handle authentification (using the default Django authentification system)
- URLsView: to list the urls availables
Usage
from django.urls import path
from django_modelapiview.views import LoginView, URLsView
Errors
If you get a "Verb not implemented" reason from your endpoint but you are sure to have defined it.
You probable just forgot the -> APIResponse
return type hint.