pythondjangodjango-rest-framework

How to retrieve singleton model instance with DRF without having to provide id?


I have a django app, and I use django-solo for SingletonModel. I do have a singleton settings model:

class GeneralSettings(SingletonModel):
    allow_signup = models.BooleanField(default=True)

I want to create an API endpoint to be able to retrieve and update the settings. I currently use DRF. Using RetrieveModelMixin and UpdateModelMixin I can easily do it but then my route has to be:

.../api/settings/1 < I need to add the id.

How can I retrieve / update my settings without having to use the id (since it doesn't make sens for a SingletonModel)?

DRF view:

class GeneralSettingsViewSet(
    RetrieveModelMixin,
    UpdateModelMixin,
    GenericViewSet,
):
    queryset = GeneralSettings.objects.all()
    serializer_class = GeneralSettingsSerializer
    http_method_names = ["get", "put"]

    def get_object(self) -> GeneralSettings:
        return GeneralSettings.get_solo()

Router:

router.register(r"settings", GeneralSettingsViewSet, "api-settings")


Solution

  • You can use custom router to solve your problem. Below is an example of what this might look like:

    from rest_framework.routers import Route, SimpleRouter  
      
      
    class SingletonRouter(SimpleRouter):  
        routes = [  
            Route(  
                url=r'^{prefix}{trailing_slash}$',  
                mapping={  
                    'get': 'retrieve',  
                    'put': 'update',  
                },  
                name='{basename}-detail',  
                detail=True,  
                initkwargs={'suffix': 'Instance'}  
            ),  
        ]  
      
      
    router = SingletonRouter()  
    router.register(r'settings', GeneralSettingsViewSet, 'api-settings')
    

    It should work now:

    GET .../settings/
    PUT .../settings/