Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)?

I have my CRUDs with models, serializares and views.

# models.py

from django.db import models


class Author(models.Model):
    slug = models.SlugField(primary_key=True)
    name = models.CharField(max_length=200)
    description = models.TextField()

    class Meta:
        db_table = 'authors'


class Phrase(models.Model):
    author_slug = models.ForeignKey(Author, db_column='author_slug', on_delete=models.DO_NOTHING)
    text = models.TextField()

    class Meta:
        db_table = 'phrases'
    
# serializers.py

from rest_framework import serializers
from .models import Author, Phrase


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('slug', 'name', 'description')


class PhraseSerializer(serializers.ModelSerializer):
    author = AuthorSerializer(source='author_slug', read_only=True,)

    class Meta:
        model = Phrase
        fields = ('id', 'text', 'author_slug', 'author')

# views.py
from rest_framework import viewsets
from .models import Author, Phrase
from .serializers import AuthorSerializer, PhraseSerializer


class AuthorViewSet(viewsets.ModelViewSet):
    serializer_class = AuthorSerializer
    queryset = Author.objects.all()


class PhraseViewSet(viewsets.ModelViewSet):
    serializer_class = PhraseSerializer
    queryset = Phrase.objects.all()

Now i need to do a new specify endpoint GET /exist-relationship-bwt-author-phrase when this body:

{
  "author_slug": "an-author",
  "phrase_slug": "a-phrase"
}

Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)?

Answer

Yes, creates a new serializer with this format:

class CheckRelationshipAuthorPhraseSerializer(serializers.Serializer):
    author_slug = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all())
    phrase_slug = serializers.PrimaryKeyRelatedField(queryset=Phrase.objects.all())

And on your view use:

class CheckRelationshipAuthorPhraseView(views.APIView):
    def post(self, request, *args, **kwargs):
        # Validate automatic entry data
        serializer = CheckRelationshipAuthorPhraseSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # Check relationship between author and phrase