django-partial-index
django-partial-index copied to clipboard
Add a validation mixin for DRF Serializers (can elaborate on this)
Hi there, can you elaborate more on this future plan?
Add a validation mixin for DRF Serializers
By the way, this is a great plugin. Thanks. Adding it to my project now.
UPDATE:
I now realize what you mean and I need this. Is there a workaround for this?
My workaround is:
models.py
from partial_index import PQ, PartialIndex, ValidatePartialUniqueMixin
from versions.models import Versionable
class VersionedWBSElement(ValidatePartialUniqueMixin, Versionable):
# wbs number is unique regardless
wbs_number = models.CharField(max_length=100)
wbs_description = models.TextField()
class Meta:
indexes = [
PartialIndex(fields=['wbs_number'], unique=True, where=PQ(version_end_date__isnull=True))
]
serializers.py
from django.core.exceptions import ValidationError
from rest_framework import serializers
from dynamic_rest.serializers import DynamicModelSerializer
class VersionedWBSElementSerializer(DynamicModelSerializer):
wbs_number = serializers.CharField()
def validate_wbs_number(self, wbs_number):
try:
VersionedWBSElement(wbs_number=wbs_number).validate_unique()
## I added try-except in order to overwrite the error message
except ValidationError as e:
raise serializers.ValidationError("This WBS number already exists.")
return wbs_number