Blog | The SilverLogic | TSL

DRF Fundamentals: Permissions and Filters

Written by Marketing Team | Dec 12, 2023 3:33:09 PM

Introduction

This blog follows up on our recent DRF Fundamentals: Permissions and Filtering workshop (watch it here), led by TSL software engineer, Pedro Tibúrcio. The basics of setting up permissions, using DRF's permission classes, creating custom permissions, and implementing filtering were discussed. Specifically, Pedro covered:

1. Permissions:
  • Concepts: Covers the association of a request with identifying credentials (Authentication), determining access based on rules (Permissions), and access control based on request rate (Throttling)
  • Process Flow: The sequence is Authentication => Permissions => Throttling
  • Note: Authentication is always checked if an auth token is provided
2. Setting up Permissions:
  • Global Permission Policy: The absence of a global policy defaults all views with unset permissions to allow any request
  • View Permission Policy: Overrides global permissions and can use Python bitwise operators in the permission_classes list
3. DRF Permission Classes:
  • Built-in Classes: Includes AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly, DjangoObjectPermissions
  • Functionality: Each class offers different levels of access control, from allowing any request to restricting access based on user authentication and model permissions
4. Custom Permissions:
  • Implementation: Involves subclassing DRF's BasePermission class and implementing has_permission and has_object_permission methods
  • Application Scenarios: Explains the behavior when applied to different view sets like ListModelMixin, RetrieveModelMixin, and custom action views
5. Basic Filtering:
  • Mechanism: In GET method views, the get_queryset method determines which data to return. It defaults to fetching all entries or a specified instance
  • Customization: Filters can be applied by overriding the get_queryset method
6. DRF Filter Backends:
  • Integration: Requires django-filters installation. Includes SearchFilter and OrderingFilter for text fields and ordering capabilities
  • Configuration: Involves setting filter backends globally or per view and configuring search and ordering parameters
7. Custom Filters:
  • Methods: Involves subclassing BaseFilterBackend or FilterSet
  • Functionality: Provides granular control over filters with various field types and custom search functions