I have the following to validate data from POST requests and I wanted to ask whether this follows best practices for Python, Django, OOP, and DRF. Any advice is highly appreciated
urls.py
and views.py
are similar to most apps.
# ---- models.py ---- #
class User(AbstractUser):
...
phone_number = models.CharField(max_length=20, null=True)
email = models.EmailField(unique=True, null=True)
# ---- serializers.py ---- #
from .models import *
from rest_framework import serializers
from .validator import Validator
class GenericSerializer(Validator, serializers.HyperlinkedModelSerializer):
...
def validate(self, data: dict) -> dict:
return super().validate(data)
class UserSerializer(GenericSerializer):
class Meta:
model = User
fields = [
"email",
"phone_number",
...
]
# ---- validator.py ---- #
from rest_framework.serializers import ValidationError
class Validator:
def validate(self, data: dict) -> dict:
match self.__class__.__name__:
case "UserSerializer":
return self.validate_user(data)
...
return data
def validate_user(self, data: dict) -> dict:
if not (data["email"] or data["phone_number"]):
raise ValidationError(
{
"email": "Must provide either email or phone number",
"phone_number": "Must provide either email or phone number",
}
)
return data
...