首页 > 解决方案 > run some function after taking input from api django

问题描述

I have one webapp where user post image and then opencv calculate its details like width, height and show back. I got this from webapp but when I trying to get the same with API I can't figure out how should I do this here my code:

Serializers.py

from rest_framework import serializers  
from results.models import Result
import cv2


class ImageSerializer(serializers.ModelSerializer):
class Meta:
    model = Result
    fields = ('title','pub_date','medium','compound','detail','outputval','image','uploader')

models.py:

class Result(models.Model):
   title = models.CharField(max_length=200)
   pub_date = models.DateField()
   medium = models.CharField(max_length=200)
   compound = models.CharField(max_length=200)
   detail = models.TextField()
   outputval = models.TextField(default='rsult not calculated', null=True, blank=True)
  image = models.ImageField(upload_to='images/')
  uploader = models.ForeignKey(User, on_delete=models.CASCADE) # will be changed to not delete in update

views.py:

from rest_framework import viewsets
from .serializers import ImageSerializer
from results.models import Result


class ImageViewSet(viewsets.ModelViewSet):
  queryset = Result.objects.all()
  serializer_class = ImageSerializer

opencv function:

def opencv(self,img_path):
    image = cv2.imread(img_path)
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    values = (" the height is %s , width is %s and number of channels is %s" % (height, width, channels)) 
    return values

what i want to do take image as user input and show the output in outputval fields.

标签: pythondjangoopencvdjango-rest-framework

解决方案


序列化程序.py

from results.models import Result
import cv2


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Result
        fields = '__all__'

    def create(self, validated_data):
        instance = super().create(validated_data)
        instance.outputval = opencv(instance.image.path)
        instance.save()
        return instance

我想是这样的。这样,当 ModelViewSet 上的 create 函数返回序列化程序的数据时,您的outputval 就会被填充。


推荐阅读