Django rest framework 如何使用graphene django将旧图像更改为新图像?

Django rest framework 如何使用graphene django将旧图像更改为新图像?,django-rest-framework,graphene-django,Django Rest Framework,Graphene Django,我想使用graphene django将旧图像更改为新图像 在我的数据库中,有一张图片的id为1。 我想更改图片,这意味着我想制作一张id为1的新图片 这是我的变异: class ImageAndSelfMutation(graphene.Mutation): class Arguments: image = Upload() Output = types.EditProfileResponse def mutate(self, info, image

我想使用graphene django将旧图像更改为新图像

在我的数据库中,有一张图片的id为1。 我想更改图片,这意味着我想制作一张id为1的新图片

这是我的变异:

class ImageAndSelfMutation(graphene.Mutation):
    class Arguments:
        image = Upload()

    Output = types.EditProfileResponse

    def mutate(self, info, image, **kwargs):
        user = info.context.user
        ok = True
        error = None

        if user.is_authenticated is not None:
            try:
                first_image = models.Photo.objects.get(owner=user, order="first")
                create_image = models.Photo.objects.create(image=image[0], owner=user)

                serializer = serializers.ImageSerializer(first_image, data=create_image)

                if serializer.is_valid():
                    serializer.save(owner=user)

            return types.EditProfileResponse(ok=ok, error=error)
        else:
            error = '로그인이 필요합니다.'
            return types.EditProfileResponse(ok=not ok, error=error)
这段代码生成一些id为2的新数据,但我不想生成新数据。我想更改1照片的id。
有人能帮我吗?

更改实例的id是个坏主意。新的id值应该在数据库中按顺序生成。您可以使用新图像复制上一个实例,然后删除上一个实例,而无需更改id:

previous_id = first_image.id
first_image.id = None
first_image.image = image[0]
first_image.save()
models.Photo.objects.filter(id=previous_id).delete()

更改实例的id是个坏主意。新的id值应该在数据库中按顺序生成。您可以使用新图像复制上一个实例,然后删除上一个实例,而无需更改id:

previous_id = first_image.id
first_image.id = None
first_image.image = image[0]
first_image.save()
models.Photo.objects.filter(id=previous_id).delete()