[Answered ]-UniqueValidator with source field

2👍

By default, the UniqueValidator expects that the source (or field name, if no source is given) can be used in the queryset that is provided to filter out the existing object. So by using a source that spans a relation (and has a dot), it will try to use that name when filtering the queryset which fails, as you’ve noticed.

You can fix this by subclassing UniqueValidator to override the filter_queryset method to filter it differently.

class CustomUniqueValidator(UniqueValidator):

    def filter_queryset(self, value, queryset):
        """
        Filter the queryset to all instances matching the given attribute.
        """
        filter_kwargs = {"email": value}
        return queryset.filter(**filter_kwargs)

This hard codes email as the filter, one possible option for not hard coding it would be to split self.field_name and get the last part of the dotted source.

Leave a comment