0

我使用 django==3.1.4 和 graphene==2.1.8 创建了如下更新突变:

# models.py
class CustomUser(AbstractUser):
    # email = models.EmailField()
    firebase_id = models.CharField(max_length=50, null=True)
    nickname = models.CharField(max_length=50, null=True)
    name = models.CharField(max_length=20, null=True)
    gender = models.IntegerField(choices=Gender, default=3)
    phone = models.CharField(max_length=20, null=True)
    birthday = models.DateField(default=datetime(2020,1,1))
    address = models.CharField(max_length=200, null=True)
    profile_image = models.ImageField(default='default-avatar.png', upload_to='users/',
                                  null=True, blank=True)
class UpdateMember(graphene.Mutation):
    class Arguments:
        firebase_id = graphene.String(required=True)
        nickname = graphene.String()
        name = graphene.String()
        gender = graphene.Int()
        phone = graphene.String()
        birthday = graphene.Date()
        address = graphene.String()
        profile_image = graphene.String()

    class Meta:
        exclude = ["password"]

    member = graphene.Field(MemberType)
    success = graphene.Boolean()

    # @login_required
    @staticmethod
    def mutate(root, info, firebase_id, **kwargs):
        success = False
        member_instance = CustomUser.objects.get(firebase_id=firebase_id)

        if member_instance:
            print(member_instance)
            success = True
            for k, v in kwargs.items():
                member_instance.k = v
            member_instance.save()

            return UpdateMember(member=member_instance, success=True)
        else:
            return UpdateMember(member=None, success=False)

在下面运行 GQL:

mutation {
  updateMember(
    firebaseId:"777",
    name:"JJJJ")
  
  {
    success
    
  }
}

回复:

{
  "data": {
    "updateMember": {
      "success": true
    }
  }
}

但是我检查了数据库,似乎没有变化,我认为.save()应该完成对数据库的持久更改的工作......

创建会员工作正常。使用 PostgresQL

谁能弄清楚为什么?

4

1 回答 1

0

您的代码中有几个问题:

  1. 您不能使用这样的字符串分配模型字段。看到这个线程
for k, v in kwargs.items():
   member_instance.k = v
   member_instance.save()

目前,您与for 循环member_instance.k中的变量无关。k

  1. firebase_id字段应该是唯一的。目前你打电话CustomUser.objects.get(firebase_id=firebase_id)是有风险的,因为 firebase_id 不是唯一的字段。Multiple objects如果您有多个使用相同 ID 保存的 CustomUser,这可能会导致错误。要修复它,只需定义:
class CustomUser(AbstractUser):
    # email = models.EmailField()
    firebase_id = models.CharField(max_length=50, unique=True)
    ...

检查你member_instance是否真的更新了。例如,您可以在保存之前打印出值,并在最终实施之前运行一些测试用例。例如:

if member_instance:
            print(member_instance)
            success = True
            for k, v in kwargs.items():
                member_instance.k = v
                print(member_instance.k)
                print(k)
                print(getattr(member_instance, k))
            member_instance.save()
于 2021-01-25T09:07:22.583 回答