Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework validate slug field

I have defined a serializer like this:

class ActivitySerializer(serializers.ModelSerializer):
      activity_project = serializers.SlugRelatedField(queryset=Project.objects.all(), slug_field='project_name')

activity_tags = serializers.SlugRelatedField(queryset=Tag.objects.all(), slug_field='tag_name', many=True)
class Meta:
    model = Activity
    fields = ('activity_name', 'activity_description', 'activity_status', 'activity_completion_percent', 'activity_due_date', 'activity_project', 'activity_tags',)

Now if I insert an activity_tag that does not exist in the database, I get a validation error"

{
    "activity_tags": [
        "Object with tag_name=test does not exist."
    ]
}

I would like to create a validation method that adds the tag in the database if it does not exist. I have tried using the

def validate(self, attrs): 
    ....

method, but apparently for a slug field there is a method that is called before this one.

Can someone point me to the right method I should use? Would this method be called in the corresponding view?

like image 553
badtrains Avatar asked May 19 '26 08:05

badtrains


1 Answers

I managed to do this by subclassing SlugRelatedField and overriding "to_internal_value" method. In the original implementation this method tries to get an object from the queryset, and if an object doesn't exist it fails the validation. So instead of calling "get" method, I'm calling "get_or_create":

class CustomSlugRelatedField(serializers.SlugRelatedField):
    def to_internal_value(self, data):
        try:
            obj, created = self.get_queryset().get_or_create(**{self.slug_field: data})
            return obj
        except (TypeError, ValueError):
            self.fail('invalid')
like image 73
Vitali Kaspler Avatar answered May 22 '26 10:05

Vitali Kaspler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!