DEV Community

Cover image for πŸ” Mapping Records to Users in Django Rest Framework (DRF)
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

1

πŸ” Mapping Records to Users in Django Rest Framework (DRF)

When building APIs with Django Rest Framework, one common requirement is to make sure each user only sees their own data.

In this tutorial, we’ll walk through how to map records to authenticated users, filter them correctly, and secure your API endpoints. Whether you’re building a dashboard, CRM, or SaaS app β€” this guide will help you do it right.

πŸŽ₯ Watch the full tutorial here:


🚧 The Problem

By default, your API might expose all records in a model to any authenticated user. That’s a privacy and security risk β€” especially for multi-user apps.

We need a way to:

  • Automatically assign a record to the logged-in user
  • Filter querysets so users only see their own records
  • Prevent unauthorized access through permission checks

βœ… The Solution

Here's how to fix that in DRF πŸ‘‡


1. Connect Your Model to the User

from django.contrib.auth.models import User
from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

2. Customize perform_create() in Your View

from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    serializer_class = TaskSerializer

    def get_queryset(self):
        return Task.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
Enter fullscreen mode Exit fullscreen mode

3. Use Permission Classes (Optional but Recommended)

from rest_framework.permissions import IsAuthenticated

class TaskViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]
    ...
Enter fullscreen mode Exit fullscreen mode

🎯 Key Takeaways

  • Use a ForeignKey to link records to the User
  • Filter the queryset using self.request.user
  • Use perform_create() to set the user during object creation
  • Add permissions to secure your endpoints

🧠 Bonus Tips

Want to go even further?

  • πŸ”„ Add IsOwnerOrReadOnly permission class
  • πŸ‘₯ Implement team or group-based access
  • πŸ” Use Django signals for advanced automation

Let me know in the comments of the video if you'd like a tutorial on any of these!


πŸ“Ί Watch the Full Tutorial

This video walks you through everything step-by-step with real code and examples.


πŸ”– Tags

#DjangoRestFramework #DRF #Python #BackendDevelopment #API #UserAuthentication #WebDevelopment


Have questions or feedback? Drop a comment under the video or reach out on LinkedIn.

Happy coding! πŸš€

Top comments (0)