python – displaying data from the database via RestAPI

Question:

Hello! I have an API that implements adding objects via a request at 127.0.0.1:8000/my_api/objects/ . Please tell me how to display objects from the database when requesting the address 127.0.0.1:8000/my_api/objects/X . Where X is the id object from the database.

The serializer looks something like this:

class MySerializer(ModelSerializer):
    type = ChoiceField(Device.TYPE_CHOICES, required=True)
    status = BooleanField(default=True)
    created_at = DateTimeField(read_only=True)

    class Meta:
        model = Object
        fields = ('id', 'type', 'name', 'status', 'created_at')

The View looks something like this:

class DevicesViewSet(GenericAPIView, ViewSetMixin, ListModelMixin, RetrieveModelMixin, CreateModelMixin):
    http_method_names = ['post']
    queryset = Object.objects
    serializer_class = MySerializer

But in fact, this code is used to implement the functionality for adding new records to the database.

Answer:

Replace all mixins in the view with one of the ReadOnlyModelViewset viewsets if you only need to display objects by GET request or ModelViewSet if you also need to change objects. In fact, these are classes of aggregators that are assembled from these mixins, which send appropriate requests to the necessary methods using routers.

from rest_framework import viewsets

class DevicesViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Object.objects.all()
    serializer_class = MySerializer

in urls.py specify the router for the view:

from rest_framework import routers

router = routers.DefaultRouter()
router.register('objects', DevicesViewSet)

urlpatterns = router.urls

This is enough to build an api for the Object model.

GET /objects/ – list of objects.

GET /objects/:id – one object

Scroll to Top