Django非primary_key自动字段 [英] Django non primary_key AutoField

查看:39
本文介绍了Django非primary_key自动字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在迁移Oracle数据库并对其进行必要的更改,其中一项主要更改是我们向所有模型(隐藏到客户端)添加了 UUIDField 作为primary_key,并且添加)常规的 AutoField .

We're migrating and making necessary changes to our Oracle database, one major change is that we're adding an UUIDField as primary_key to all models(hidden to the client), and(trying to add) a regular AutoField.

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

We found that displaying the primary_key directly to our clients wasn't good design, but they also requested an ID field displayed to reference objects more easily, but Django limits this by not allowing AutoField to NOT be the primary_key

是否有解决此问题的方法?

Is there a workaround for this issue?

推荐答案

我认为可行的方法是使用 IntegerField (几乎是 AutoField 在后台使用的功能)),并在模型首次保存之前(在将其存入数据库之前)将其递增.

What I think could work is using an IntegerField (pretty much what an AutoField uses under the hood), and increment that on the model's first save (before it's ever put into the database).

我写了一个示例模型在下面显示.

I wrote an example model to show this below.

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 的内容,只是使用不同的模型字段.

This, in theory, just replicates what AutoField does, just with a different model field.

这篇关于Django非primary_key自动字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆