python - Django 模型中的自定义 id 字段

标签 python django

我正在用 Django 制作一个 Web 应用程序。我想在我的模型中使用自定义 id 字段并且我知道 uuid 模块。问题是我不知道把这个逻辑放在哪里。我不想使用 Django 的 AutoField。我希望它是这样的,如果输入一行,那么这个 id 字段必须是自定义的,而不是 AutoField。我想到一个愚蠢的想法是在使用我的自定义 id 插入行后更改 id 字段。谁能帮我解决这个问题。非常感谢任何帮助。

最佳答案

https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields

If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.

所以你想要(来自 https://docs.djangoproject.com/en/dev/ref/models/fields/#uuidfield )

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

我认为您不必将字段命名为 id

关于python - Django 模型中的自定义 id 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109940/

相关文章:

python - 平滑分类输出

python - 从变量和另一个列表创建列表的正确方法是什么?

python - 有没有更好的方法来覆盖 Marshmallow.fields.List?

python - 分发需要最小 Python 版本的 Python 包的最佳方法是什么

python - 如何使用 django 创建一个 View 来记录数据库中 ModelMultipleChoiceField 表单的数据?

Django Azure AD 集成

python - 如何在 JSON 中获取 PrimaryKeyRelatedField 的字符串表示形式

javascript - 如何使用 javascript 而不是 Django session 将表单数据(Django 表单)存储到浏览器的本地存储?

python - 检测空 XML 根元素

django - 如何在单个帖子中更新多个实例 - django rest framework