我遇到的情况是,ForeignKey
的 object_id
接受 PositiveIntegerField
,但我的模型的所有 id
均已设置作为uuid
。
我查阅了文档,发现我应该使用 get_prep_value(value)
或 get_db_prep_value(value, connection, prepared=False)¶
问题是我到底应该怎么做?
这是包含foreignRelation
的模型代码
target_ct = models.ForeignKey(ContentType,
blank=True,
null=True,
related_name='target_obj',
on_delete=models.CASCADE)
target_id = models.PositiveIntegerField(null=True,
blank=True,
db_index=True)
target = GenericForeignKey('target_ct', 'target_id')
created_at = models.DateTimeField(auto_now_add=True,
db_index=True)
所有其他模型的字段
id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
每当我尝试使用当前设置保存模型时,我都会收到此错误
django.db.utils.DataError: integer out of range
最佳答案
您也将其设为UUIDField
:
class MyModel(models.Model):
target_ct = models.ForeignKey(
ContentType,
blank=True,
null=True,
related_name='target_obj',
on_delete=models.CASCADE
)
target_id = models.<b>UUIDField(</b>
null=True,
blank=True,
db_index=True
<b>)</b>
target = GenericForeignKey('target_ct', 'target_id')
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
然后您就可以引用以 UUIDField
作为主键的所有对象。
这正是使用 AutoField
作为主键通常更好的原因之一:如果所有模型都具有相同的主键,您可以用它引用所有对象。现在,您只能引用以 UUIDField
作为主键的模型。
关于Django ContentTypes 将 uuid 字段转换为整数字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61562666/