• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? Mapping Records to Users in Django Rest Framework (DRF)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
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
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)
3. Use Permission Classes (Optional but Recommended)


from rest_framework.permissions import IsAuthenticated

class TaskViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
...
? 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

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.

Happy coding! ?


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу