【问题标题】:How do I change old Image to New image by using graphene-django?如何使用 graphene-django 将旧图像更改为新图像?
【发布时间】:2020-03-29 11:00:13
【问题描述】:

我想使用 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。 谁能帮帮我?

【问题讨论】:

    标签: django-rest-framework graphene-django


    【解决方案1】:

    更改实例的 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2015-04-01
      • 1970-01-01
      • 2012-07-22
      • 2020-06-06
      相关资源
      最近更新 更多