保存一次数据(以便能够将图像加载到服务器),然后在进行一些更改后更新同一实例

时间:2019-05-08 14:45:53

标签: django django-rest-framework

我第一次保存发布请求中的数据,因为我需要像“ upload_image”功能建议的那样将图像上传到服务器。 同时,我有几个字段为空,并且需要通过一些外部函数获得一些值。 然后,我需要将整个对象保存在数据库中。

我面临的问题是它将数据两次保存在数据库中。 并且第一个保存的对象的所有属性都为null,但passengerPhoto,passportPassport和agent除外。 (顺便说一句没有错误)

有什么想法吗? 非常感谢!

#VIEW
class IdentityCheckView(CreateAPIView, generics.ListAPIView):

    serializer_class = IdentityCheckSerializer
    permission_classes = [permissions.AllowAny]

    def get_queryset(self):
        request = self.request
        qs = IdentityCheck.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs = qs.filter(name__icontains=query)
        return qs

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        if(serializer.is_valid()):
            res = self.create(request, *args, **kwargs)
            image = FaceRecognition.imageMatch(res.data['passengerPhoto'], res.data['passengerPassport'])
            wanted = WantedPro.criminalMatch(res.data['passengerPhoto'])

            passport_json = OCR.passportMatch(res.data['passengerPassport'])
            image_json = json.loads(image)


            firstName      = passport_json['names']
            lastName       = passport_json['surname']
            nationality    = passport_json['country']
            birthDate      = passport_json['date_of_birth']
            gender         = passport_json['sex']
            ableToBoard    = bool(wanted) & bool(image_json['match']) & bool(passport_json['valid_expiration_date'])


            serializer.update(
                                id=res.data['id'],
                                firstName=firstName,
                                lastName=lastName,
                                nationality=nationality,
                                birthDate=birthDate,
                                gender=gender,
                                ableToBoard=ableToBoard)



        return Response({"image": image_json, "passport": passport_json, "wanted": wanted}, status=200)

    def perform_create(self, serializer):
        res = serializer.save(agent=self.request.user)



#SERIALIZER
class IdentityCheckSerializer(serializers.ModelSerializer):

    class Meta:
        model = IdentityCheck
        fields = '__all__'
        read_only_fields = ['agent', 'id']


#MODEL
def upload_image(instance, filename):
    return "media/check/{agent}/{date}/{filename}".format(agent=instance.agent,date=datetime.datetime.today().strftime('%d-%m-%Y'), filename=filename)


class IdentityCheckQuerySet(models.QuerySet):
    pass

class IdentityCheckManager(models.Manager):
    def get_queryset(self):
        return IdentityCheckQuerySet(self.model,using=self._db)

class IdentityCheck(models.Model):
    agent               = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    passengerPhoto      = models.ImageField(upload_to=upload_image, null=False, blank=False)
    passengerPassport   = models.ImageField(upload_to=upload_image, null=False, blank=False)
    lastName            = models.CharField(max_length=255, null=True, blank=True)
    firstName           = models.CharField(max_length=255, null=True, blank=True)
    birthDate           = models.DateField(null=True, blank=True)
    nationality         = models.CharField(max_length=255, null=True, blank=True)
    gender              = models.CharField(max_length=1, null=True, blank=True)
    ableToBoard         = models.BooleanField(null=False, blank=False, default=False)
    timestamp           = models.DateTimeField(auto_now_add=True)

    objects = IdentityCheckManager()

0 个答案:

没有答案