我使用的是Python 3.8和Django 3.0。
Models.py
class CustomeUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
class ActivationCode(models.Model):
Code = models.CharField(max_length=30, null=False, unique=True)
ForUser = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.CASCADE)
...代码:
jj = {'app_id': '100',
'color': 'blue',
'os_type': 'MacOS',
'time': '1596397345',
'regKey': 'dJbeetbQ',
'os_version': '10.15.6',
'place_id': '20190228-3',
'version': '2.0.0.8',
'guid': '10614ba9b54f909a715ed518cc39741811369a11',
'randomString': '3808651424'}
regKey = jj["regKey"]
record = ActivationCode.objects.get(Code=regKey)当regKey与用户记录匹配时,将出现异常。如果ForUser字段为空,它将通过。
这里有什么问题?
完整回溯:
Traceback (most recent call last):
File "C:\Users\Ken\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-59-b3b355ae1522>", line 1, in <module>
ActivationCode.objects.get(Code=regKey)
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\query.py", line 411, in get
num = len(clone)
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\query.py", line 258, in __len__
self._fetch_all()
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\query.py", line 74, in __iter__
for row in compiler.results_iter(results):
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line 1088, in apply_converters
value = converter(value, expression, connection)
File "C:\Users\Ken\anaconda3\lib\site-packages\django\db\backends\mysql\operations.py", line 270, in convert_uuidfield_value
value = uuid.UUID(value)
File "C:\Users\Ken\anaconda3\lib\uuid.py", line 160, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string发布于 2020-08-03 14:00:58
这个错误的根本原因只是因为您在ForUser_id列中有一个non-UUID值。
正如你在评论中所说的
我有一些记录,它们是空的。但没有坏数据。
在我看来,null似乎是导致这个错误的原因。也不建议UUIDField使用null值,而是使用空字符串的值约定。Using the null and blank field options上的博客值得一读。
发布于 2020-08-04 23:51:28
我已经知道出了什么问题。
这个问题是由我使用UUID()在MySQL服务器中更新的一些用户记录引起的。但是MYSQL中的UUID()是36字节,而Django中的UUID字段是32字节。
现在我用id = UUID().Replace('-','')再次更新了id,然后这个问题就解决了。
https://stackoverflow.com/questions/63220786
复制相似问题