0

当用户想要更新之前创建的用户模型时,我正在尝试更新用户模型的各个字段。我有一个自定义用户模型,我正在使用 django rest 框架来更新 api。

视图.py

class UserUpdate(generics.UpdateAPIView):
    """
    Update user.
    """
    parser_class = (FileUploadParser,)
    permission_classes = (AllowAny,)
    queryset = User.objects.all()
    serializer_class = UserUpdateSerializer

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.user_id = request.data.get("user_id")
        instance.save()
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)

模型.py

class User(models.Model):
    USER_CHOICES = (
        (1, u'ADMIN'),
        (2, u'SALES'),
        (3, u'KITCHEN'),
        (4, u'EMPLOYEE'),
    )
    image = models.ImageField(upload_to='employees/', null = True, blank = True)
    name = models.CharField(max_length=50)
    user_id = models.CharField(max_length=30, primary_key = True, blank = False)
    email = models.CharField(max_length=50)
    password = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    user_group = models.PositiveSmallIntegerField(default=4, choices=USER_CHOICES)
    firebase_token = models.CharField(max_length=150, default=None, null = True)
    shop =  models.ForeignKey(Shop, on_delete=models.SET_DEFAULT, default=None)
    phone = PhoneField(blank=False, default=0)

序列化程序.py

class UserUpdateSerializer(serializers.ModelSerializer):
    shop = serializers.CharField()
    class Meta:
        model = User
        fields = ('image', 'url', 'phone', 'name', 'user_id','email', 'password', 'is_active', 'user_group', 'shop')

    def update(self, instance, validated_data):
        shop = validated_data.pop('shop')
        user_id = validated_data.pop("user_id")
        print(user_id)
        shopId = Shop.objects.filter(name=shop).values('shop_id').first()
        if shopId is not None:
            shop_id = shopId['shop_id']
            try:
                if user_id is not None:
                    instance.name = validated_data.get('name', instance.name)
                    instance.image = validated_data.get('image', instance.image)
                    instance.email = validated_data.get('email', instance.email)
                    instance.phone = validated_data.get('phone', instance.phone)
                    instance.password = validated_data.get('password', instance.password)
                    instance.user_group = validated_data.get('user_group', instance.user_group)
                    instance.shop_id = validated_data.get('shop_id', instance.shop_id)
                    instance.is_active =  True
                    instance.save()
                    return instance
                else:
                    print("Test")
            except Exception as e:
                return e
        else:
            return None

这是抛出一个错误,说用户已经存在!

请协助!

4

2 回答 2

1

只需更改您的序列化程序,如下所示

class UserUpdateSerializer(serializers.ModelSerializer):
    shop = serializers.CharField()

    class Meta:
        model = User
        fields = ('image', 'url', 'phone', 'name', 'user_id','email', 'password', 'is_active', 'user_group', 'shop')

    def update(self, instance, validated_data):
        shop = validated_data.pop('shop')
        shop_obj = Shop.objects.filter(name=shop).first()
        if shop_obj:
            instance.shop = shop_obj
        return super().update(instance, validated_data)

于 2020-01-01T08:20:27.297 回答
1

当您调用UserUpdateAPI 时,它会User为每个新的user_id. 我不知道你为什么要更新user_id。任何新user_id的都会创建一个新User实例。如果要更新 以外user_id的内容,则需要删除以下行。

  1. UserUpdate从API 视图中删除这些行。

    instance.user_id = request.data.get("user_id")       
    instance.save()
    
  2. UserUpdateSerializer

    instance.user_id = validated_data.get('user_id', instance.user_id)
    
  3. 添加lookup_field = 'user_id'UserUpdateAPI 视图

  4. user_id在 url添加,比如

    path('userupdate/<str:user_id>/', UserUpdate.as_view())
    
于 2020-01-01T06:39:14.063 回答