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

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    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")

    Continue reading...

Compartilhe esta Página