Django Rest Framework - 如何在 serializer.save 之前进行额外查询

Django Rest Framework - How to make extra query before serializer.save

我是 Django Rest Framework 的新手,我正在尝试做这个简单的事情,但我不确定该怎么做。

所以,这是我的 models.py

class Category(models.Model):

    name = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True) 
    email = models.EmailField(_('email address'), blank=True, null=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name


class Report(models.Model):

    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    description = models.TextField()
    address = models.CharField(max_length=500)
    reporter_first_name = models.CharField(max_length=250)
    reporter_last_name = models.CharField(max_length=250)
    reporter_email = models.CharField(max_length=250)
    reporter_phone = models.CharField(max_length=250)
    report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
    date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ('-date',)

    def __str__(self):
        return self.description

我在 React 中有一个表单可以提交类别 ID 等值。在将报告保存到数据库之前,我需要做的是向该类别 ID 的电子邮件地址发送一封邮件。

这是我的views.py

class ManageCategories(viewsets.ModelViewSet):
    serializer_class = CategorySerializer

    def get_object(self, queryset=None, **kwargs):
        item = self.kwargs.get('pk')
        return get_object_or_404(Category, slug=item)

    def get_queryset(self):        
        return Category.objects.all()


class ManageReports(viewsets.ModelViewSet):
    serializer_class = ReportSerializer
    parser_classes = [MultiPartParser, FormParser]

    def get_permissions(self):
        if self.action == 'create':
            self.permission_classes = [permissions.AllowAny]
        else:
            self.permission_classes = [permissions.IsAuthenticated]
        return super(self.__class__, self).get_permissions()


    def create(self, request, *args, **kwargs):
        serializer = ReportSerializer(data=request.data)
        
        if serializer.is_valid():
            data = serializer.validated_data         

            try:
                serializer.save()
                return Response({"success": "Sent"})
            except Exception as ex:
                return Response({'success': f'{ex}'})
            
        return Response({"success": serializer.errors})


    def get_object(self, queryset=None, **kwargs):
        id = self.kwargs.get('pk')
        return get_object_or_404(Report, id=id)


    def get_queryset(self):        
        return Report.objects.all()

如何从提交的类别 ID 开始获取电子邮件值?

我们可以从序列化器中获取所有经过验证的数据,如下所示:

serializer.validated_data["category"].email