Write Python Django code to create an API that fetches a value from a query parameter and inserts this value into a database.
💡 Model Answer
To implement this in Django, you can use Django REST Framework (DRF) for simplicity. First, create a model to store the value:
# models.py
from django.db import models
class Value(models.Model):
value = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)Next, create a serializer:
# serializers.py
from rest_framework import serializers
from .models import Value
class ValueSerializer(serializers.ModelSerializer):
class Meta:
model = Value
fields = ['id', 'value', 'created_at']Now, write a view that reads the query parameter and saves it:
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Value
from .serializers import ValueSerializer
class ValueCreateView(APIView):
def get(self, request, *args, **kwargs):
# Expecting ?value=some_text
val = request.query_params.get('value')
if not val:
return Response({'error': 'value query param required'}, status=status.HTTP_400_BAD_REQUEST)
# Create and serialize
instance = Value.objects.create(value=val)
serializer = ValueSerializer(instance)
return Response(serializer.data, status=status.HTTP_201_CREATED)Add a URL pattern:
# urls.py
from django.urls import path
from .views import ValueCreateView
urlpatterns = [
path('api/value/', ValueCreateView.as_view(), name='value-create'),
]Explanation & Complexity: The view performs a single database insert, so the time complexity is O(1). DRF handles request parsing, validation, and response formatting. This approach scales well for simple CRUD operations and can be extended with authentication, pagination, or more complex business logic as needed.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500