python
data_error
ai_generated
true
django.core.exceptions.ValidationError: {'model': [ValidationError(['“test” is not a valid UUID.'])]}
ID: python/django-model-foreignkey-validation
80%Fix Rate
82%Confidence
0Evidence
2024-05-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.2 | active | — | — | — |
| 4.0 | active | — | — | — |
Root Cause
外键字段赋值了非 UUID 格式的字符串,但模型期望 UUID 类型
generic中文
外键字段期望 UUID 类型,但传入了无效的字符串值
Workarounds
-
100% success 传入有效的 UUID 字符串
import uuid; model_instance.foreign_key = uuid.UUID('550e8400-e29b-41d4-a716-446655440000') -
95% success 使用 UUID 对象而不是字符串
from uuid import UUID; model_instance.foreign_key = UUID('550e8400-e29b-41d4-a716-446655440000')
Dead Ends
Common approaches that don't work:
-
忽略验证直接保存
100% fail
Django 在保存前会进行字段验证,无法绕过
-
将字段类型改为 CharField
60% fail
改变模型结构需要迁移,且可能破坏外键关系