Bas*_*deh 10 python database migration django postgresql
我正在构建一个以 UUIDField 作为主键的模型。但我的用例需要。也有一个自动增量字段。Django 提供了一个 AutoField。但是需要有 primary_key=True ,在我的情况下我不想要,因为我使用 UUIDField 作为primary_key。
我尝试创建一个字段并赋予 db_type 'serial' 并添加一个迁移,该迁移改变了在 100000 处重新启动的序列.. 使用 Admin 向数据库添加对象将始终将数字字段存储为空值。如果我删除 null=True。然后保存将失败,因为它需要数字字段的值。
如何在保持 UUIDField 作为主键的同时使数字字段递增?
fields.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'
Run Code Online (Sandbox Code Playgroud)
models.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
)
Run Code Online (Sandbox Code Playgroud)
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)
]
Run Code Online (Sandbox Code Playgroud)
小智 4
也尝试过这个。我的解决方法是使用原始 SQL。
移民:
migrations.RunSQL(
"CREATE SEQUENCE sequence_name START 100000",
reverse_sql="DROP SEQUENCE IF EXISTS sequence_name",
elidable=False,
),
Run Code Online (Sandbox Code Playgroud)
模型:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2786 次 |
| 最近记录: |