gpt4 book ai didi

python - Django 非 primary_key AutoField

转载 作者:太空狗 更新时间:2023-10-30 00:54:06 25 4
gpt4 key购买 nike

我们正在迁移我们的 Oracle 数据库并对其进行必要的更改,一个主要更改是我们将 UUIDField 添加为所有模型的主键(对客户端隐藏),并且(尝试添加) 一个常规的 AutoField

我们发现直接向我们的客户显示 primary_key 不是好的设计,但他们还要求显示一个 ID 字段以更容易地引用对象,但 Django 通过不允许 AutoField 来限制这一点 NOT成为主键

这个问题有解决方法吗?

最佳答案

我认为可行的方法是使用 IntegerField(几乎是 AutoField 在幕后使用的),并在模型第一次保存时递增它(在它保存之前)存入数据库)。

我写了一个示例模型来展示下面的内容。

from django.db import models

class MyModel(models.Model):

# This is what you would increment on save
# Default this to one as a starting point
display_id = models.IntegerField(default=1)

# Rest of your model data

def save(self, *args, **kwargs):
# This means that the model isn't saved to the database yet
if self._state.adding:
# Get the maximum display_id value from the database
last_id = self.objects.all().aggregate(largest=models.Max('display_id'))['largest']

# aggregate can return None! Check it first.
# If it isn't none, just use the last ID specified (which should be the greatest) and add one to it
if last_id is not None:
self.display_id = last_id + 1

super(MyModel, self).save(*args, **kwargs)

从理论上讲,这只是复制了 AutoField 所做的,只是使用了不同的模型字段。

关于python - Django 非 primary_key AutoField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com