【问题标题】:Django Restful: How do I update my custom user model?Django Restful:如何更新我的自定义用户模型?
【发布时间】:2019-05-29 05:18:56
【问题描述】:

我正在构建一个 API 作为大学项目的一部分,但是,我在研究如何更新我的自定义用户模型时遇到了困难。目前我有一个用于更新配置文件的序列化程序,但是当我尝试使用序列化程序更新表时,它会出现错误 1406:“第 1 行的列 'title' 的数据太长”。我目前不确定如何解决这个问题,想知道是否有人可以指出我正确的方向

更新: 因此,我似乎因为列错误而获得的数据太长,因为我拥有的代码是附加到列中,而不是在 JSON 包含字段数据时更改它们,或者如果不包含则保留它们。因此,一旦我修改了列长度,我就会得到以下数据库行:

(None, 'Anthony'), (None, (None, 'Anthony')), 1, 0, 1, 1, 2019-01-01, ('a 测试地址', 'hello'), (None, None), (None, None), edd, (None, 'boy'), (None, 'there'), (None, None), (None, '282')

有问题的型号:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    title =models.CharField(_('Title'), max_length=8, null=True,  blank=True)
    first_name=models.CharField(_('first name(s)'), max_length=100, blank =True)
    last_name=models.CharField(_('last name'), max_length=100, blank = True)
    is_active=models.BooleanField(_('account active'), default=False)
    is_driver = models.BooleanField(_('driver status'), default=False)
    is_staff = models.BooleanField(_('staff status'), default =False)
    is_admin = models.BooleanField(_('admin status'), default =False)

    dob = models.DateField(auto_now_add= True, blank=True)
    address_1=models.CharField(_('address line 1'),max_length=60, null=False, blank=False)
    address_2=models.CharField(_('address line 2'),max_length=60, null=True, blank=True)
    address_3=models.CharField(_('address line 3'),max_length=60, null=True, blank=True)
    city = models.CharField(_('city'),max_length=60, null=False, blank=False)
    county = models.CharField(_('county'),max_length=60, null=False, blank=False)
    postcode = models.CharField(_('postcode'),max_length=8, blank=False, null=False)
    phone_no = models.CharField(_('phone number'),max_length=50, null=True, blank=True)
    mobile_no = models.CharField(_('mobile Number'),max_length=50,null=False, blank=False)
    drivers_licence_number = models.CharField(max_length=30, null=True, blank=True)
    taxi_licence_number=models.CharField(max_length=30, null=True, blank=True)
    driver_photo=models.ImageField(blank=True)
    date_joined=models.DateField(auto_now_add=True, blank=True)
    last_update=models.DateField(auto_now_add=True, blank=True)

有问题的序列化程序:

class UserProfileSerializer (serializers.ModelSerializer):
    model = User

    id = serializers.IntegerField(read_only=True)
    dob = serializers.DateField(read_only=True)
    title=serializers.CharField(max_length=8, required=False)
    first_name=serializers.CharField(max_length=80,required=False)
    last_name=serializers.CharField(max_length=80,required=False)
    address_1 = serializers.CharField(max_length=100, required=False)
    address_2 = serializers.CharField(max_length=100,required=False)
    address_3 = serializers.CharField(max_length=100,required=False)
    postcode = serializers.CharField(max_length=10, required=False)
    county = serializers.CharField(max_length=50, required=False)
    city = serializers.CharField(max_length=50, required=False)
    phone_no = serializers.CharField(required=False)
    mobile_no = serializers.CharField(required=False)




    def update (self, instance, validated_data):
        instance.title= validated_data.get('title'), instance.title
        instance.first_name = validated_data.get('first_name'), instance.first_name
        instance.last_name = validated_data.get('last_name'), instance.first_name
        instance.address_1 = validated_data.get('address_1'), instance.address_1
        instance.address_2 = validated_data.get('address_2'), instance.address_2
        instance.address_3 = validated_data.get('address_3'), instance.address_3
        instance.postcode = validated_data.get('postcode'), instance.postcode
        instance.county = validated_data.get('county'), instance.county
        instance.phone_no = validated_data.get('phone_no'),instance.phone_no
        instance.mobile_no = validated_data.get('mobile_no'), instance.mobile_no
        instance.last_update = datetime.now()

        instance.save()
    return instance

有问题的视图:

class UpdateProfile(APIView):
    permission_classes=[permissions.IsAuthenticated]

    def post(self, request, format=None):

        user=request.user
        print (user.id)
        query_set=User.objects.get(id=user.id)
        print("we got a queryset")
        print(query_set)

        serializer=UserProfileSerializer(query_set, data=request.data)


        if serializer.is_valid():

            profile = serializer.save()

            if profile:        
                return Response(user.data, status=status.HTTP_200_OK)

        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

从服务器控制台跟踪:

内部服务器错误:/editprofile/ Traceback(最近调用 最后):文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py", 第 85 行,在 _execute 返回 self.cursor.execute(sql, params) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\mysql\base.py” , 第 71 行,在执行中 return self.cursor.execute(query, args) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py", 第 250 行,执行中 self.errorhandler(self, exc, value) 文件 "C:\Users\clin\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py", 第 50 行,在默认错误处理程序中 引发错误值文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py”, 第 247 行,执行中 res = self._query(query) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py", 第 412 行,在 _query 中 rowcount = self._do_query(q) 文件 "C:\Users\clin\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py", 第 375 行,在 _do_query db.query(q) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py", 第 276 行,查询中 _mysql.connection.query(自我,查询) _mysql_exceptions.DataError: (1406, "Data too long for column 'title' at row 1")

上述异常是以下异常的直接原因:

Traceback(最近一次调用最后一次):文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\exception.py", 第 34 行,在内部 response = get_response(request) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\base.py”, 第 126 行,在 _get_response 中 response = self.process_exception_by_middleware(e, request) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\base.py", 第 124 行,在 _get_response response = Wrapped_callback(request, *callback_args, **callback_kwargs) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\views\decorators\csrf.py” , 第 54 行,在 Wrapped_view 中 返回 view_func(*args, **kwargs) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\views\generic\base.py", 第 68 行,在视图中 return self.dispatch(request, *args, **kwargs) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py", 第 495 行,正在调度中 响应 = self.handle_exception(exc) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py”, 第 455 行,在句柄异常中 self.raise_uncaught_exception(exc) 文件 "C:\Users\clin\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py", 第 492 行,正在调度中 response = handler(request, *args, **kwargs) 文件“C:\Users\clini\git\net302API\Test1\api\views.py”,第 68 行,在帖子中 profile = serializer.save() 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\serializers.py”, 第 209 行,保存 self.instance = self.update(self.instance,validated_data) 文件“C:\Users\clini\git\net302API\Test1\api\serializers.py”,第 137 行,在 更新 instance.save() 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\contrib\auth\base_user.py", 第 73 行,保存 super().save(*args, **kwargs) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py” , 第 718 行,保存中 force_update=force_update, update_fields=update_fields) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py", 第 748 行,在 save_base 更新 = self._save_table(raw, cls, force_insert, force_update, using, update_fields) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py", 第 812 行,在 _save_table 中 强制更新)文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py”, 第 861 行,在 _do_update 中 返回过滤的._update(值)> 0 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\query.py”, 第 712 行,在 _update 中 返回 query.get_compiler(self.db).execute_sql(CURSOR) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\sql\compiler .py", 第 1383 行,在 execute_sql 中 cursor = super().execute_sql(result_type) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\sql\compiler.py", 第 1065 行,在 execute_sql 中 cursor.execute(sql, params) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py”, 第 100 行,在执行中 返回 super().execute(sql, params) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py”, 第 68 行,在执行中 返回 self._execute_with_wrappers(sql, params, many=False, executor=self._execute) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py", 第 77 行,在 _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py", 第 85 行,在 _execute 返回 self.cursor.execute(sql, params) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\utils.py", 第 89 行,在 退出 从 exc_value 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py”中提高 dj_exc_value.with_traceback(traceback), 第 85 行,在 _execute 返回 self.cursor.execute(sql, params) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\mysql\base.py” , 第 71 行,在执行中 return self.cursor.execute(query, args) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py", 第 250 行,执行中 self.errorhandler(self, exc, value) 文件 "C:\Users\clin\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py", 第 50 行,在默认错误处理程序中 引发错误值文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py”, 第 247 行,执行中 res = self._query(query) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py", 第 412 行,在 _query 中 rowcount = self._do_query(q) 文件“C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py”, 第 375 行,在 _do_query db.query(q) 文件 "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py", 第 276 行,查询中 _mysql.connection.query(self, query) django.db.utils.DataError: (1406, "Data too long for column 'title' at row 1")

【问题讨论】:

  • 看起来你设置的太长了 title - 这里你只设置了 8 个符号:title =models.CharField(_('Title'), max_length=8, null=True, blank=True)
  • 我认为可能是这种情况,但是当我向代码传递一个只有 3-4 个符号的标题值时,它会引发相同的错误。
  • 您是否尝试将title 设为空白?显示完整的错误跟踪。
  • 去掉打印语句,使用第三方应用调试你的应用

标签: django django-rest-framework serialization


【解决方案1】:

您是否可能更新了标题的 max_length 并且尚未迁移?

【讨论】:

  • 好的。我试过了,它确实有效,有点。它将数据移动到数据库,但我得到的不仅仅是“输入数据字符串”或“与以前相同的数据”,而是 (None, 'Anthony') (None, (None, 'Anthony')) 1 0 1 1 2019-01-01 ('a test address', 'hello') (None, None) (None, None) edd (None, 'boy') (None, 'there') (None, None) (None, '282')
【解决方案2】:

所以为了解决这个问题,我找到了解决方案。当我为我的序列化程序编写更新方法时,我将它们写为 instance.fieldname =validated.data.get('input_name'),instance.fieldname

他们应该在什么时候 instance.fieldname =validated.data.get('input_name',instance.fieldname)

谢谢大家的帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 2022-10-22
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 2014-02-07
    相关资源
    最近更新 更多