我正在构建一个以 UUIDField 作为主键的模型。但我的用例需要。还有一个自动增量字段。 Django 提供了一个 AutoField。但它需要有 primary_key=True ,在我的情况下,这是我不想要的,因为我使用 UUIDField 作为 primary_key。
我尝试创建一个字段并将 db_type 设置为“serial”并添加一个迁移,该迁移更改序列以在 100000 重新启动。使用 Admin 将对象添加到数据库将始终将数字字段存储为空值。如果我删除 null=True。然后保存将失败,因为它需要数字字段的值。
如何在保持 UUIDField 作为主键的同时使数字字段递增?
字段.py
class SerialField(models.Field):
description = _("BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE")
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%(value)s' value must be an integer."),
}
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
super().__init__(*args, **kwargs)
def db_type(self, connection):
return 'serial'
模型.py
from .fields import SerialField
class MyModel(models.Model):
uuid = models.UUIDField(
verbose_name=_("UUID Identifier"),
primary_key=True,
default=uuid.uuid4,
editable=False,
help_text=_("Requried, PrimaryKey none-editable"),
db_index=True,
)
number = SerialField(
primary_key=False,
editable=False,
help_text=_("Auto Increment Number"),
verbose_name=_("Number"),
#null=True
)
0002_auto_20180202.py
从 django.db 导入迁移
def forwards(apps, schema_editor):
if schema_editor.connection.alias == 'default':
return migrations.RunSQL(
"ALTER SEQUENCE app_name_mymodel_number_seq RESTART WITH 100000"
)
class Migration(migrations.Migration):
dependencies = [
('activities', '0001_initial'),
]
operations = [
migrations.RunPython(forwards)
]
最佳答案
这个也试过了。我的解决方法是改用原始 SQL。
迁移:
migrations.RunSQL(
"CREATE SEQUENCE sequence_name START 100000",
reverse_sql="DROP SEQUENCE IF EXISTS sequence_name",
elidable=False,
),
型号:
def get_next_increment():
with connection.cursor() as cursor:
cursor.execute("SELECT nextval('sequence_name')")
result = cursor.fetchone()
return result[0]
class MyModel(models.Model):
my_field = models.IntegerField(default=get_next_increment, editable=False, unique=True)
关于python - 在使用 UUID 字段作为主字段的 Django 模型中添加非主键自动字段或 'serial' 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461740/