Django ContentTypes 将 uuid 字段转换为整数字段

标签 django postgresql

我遇到的情况是,ForeignKeyobject_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/

相关文章:

postgresql - 如何使用 Homebrew 将 Postgis 安装到 Postgres@9.6 的 Keg 安装中?

postgresql - postgresql支持多少次更新记录?

python - 在 Django 中使用 JSONField 进行批量更新

python - 尝试从 Django ADMIN 中的外部用户模型调用 is_active 方法

ruby-on-rails - 如何使用 PostgreSQL 全文搜索返回部分短语匹配而不返回太多行?

sql - Postgres : Could not identify an ordering operator for type unknown

django - 将 django 密码验证器与 django rest 框架 validate_password 集成

python - Django - 存储过程不存在

python - 在 Django 中使用 inspectdb 时出错

django - Django REST Framework-将额外的参数传递给 Action