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

Time:12-17

I'm new to Django Rest Framework and I'm trying to do this simple thing, but I'm not sure how to do it.

So, this is my 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

I have a form in React that submits, among other values, the category ID. What I need to do, before saving the report to the DB, is send a mail to the email address of that category ID.

This is my 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()

How do I get the email value starting from the submited category ID?

CodePudding user response:

We can get all validated data from serializer, like as below:

serializer.validated_data["category"].email

CodePudding user response:

One way to support this is to override ReportSerializer's create method, and do your pre-save actions there:

class ReportSerializer(serializers.ModelSerializer):
    # ...

    def create(self, validated_data)
        category = validated_data['category']
        # do you stuff with category.email

        return super().create(validated_data)
  • Related