I'm new to Django and I'm trying to create a somewhat basic API. But one thing that has been bugging me is how to create a callback function for when certain (asynchronous) events occur.
For example, one of my simplest cases is for when the client sends a POST request. I would like to send back to him the ID of that request in the DB. How would I do that?
My code mostly follows William S. Vincent's Django for APIs book with minor modifications.
The most important parts are:
models.py
:
from django.db import models
class SegmentcliApi(models.Model):
request_id = models.AutoField(primary_key = True)
database = models.CharField(max_length = 100)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __str__(self):
return f'DB Request to {self.database}: created at {self.created_at}'
serializers.py
:
from rest_framework import serializers
from .models import SegmentcliApi
class SegmentcliApiSerializer(serializers.ModelSerializer):
class Meta:
fields = (
'request_id',
'database',
'created_at',
'updated_at',
)
model = SegmentcliApi
views.py
:
from rest_framework import generics
from .models import SegmentcliApi
from .serializers import SegmentcliApiSerializer
class SegmentcliApiList(generics.ListCreateAPIView):
queryset = SegmentcliApi.objects.all()
serializer_class = SegmentcliApiSerializer
class SegmentcliApiDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = SegmentcliApi.objects.all()
serializer_class = SegmentcliApiSerializer