我正在用 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/