自动递增非pk字段(从1000开始) [英] Auto Increment non-pk field starting at 1000

查看:46
本文介绍了自动递增非pk字段(从1000开始)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Django工作了大约一个星期,所以我对以下内容没有太多的想法.我需要为我的模型和postgres数据库中的字段创建一个序列,该序列会自动从1000开始递增.因此它的列表如下:1000、1001、1002等.

I have been working in Django for about a week now so I don't have much idea on the following. I need to create a sequence for a field in my model and postgres database that auto increments starting at 1000. So it would list like: 1000, 1001, 1002, etc....

根据到目前为止的研究,我需要扩展保存功能并检查数据库中的先前值.

From what I have researched so far I would need to extend the save function and check the previous value in the db.

最终结果是能够使用此模型发布到API,并且该字段的值如上所述递增.

The end result is to be able to post to an API using this model and this field increments like above.

class MyModel(AuditMixin, models.Model):
    order_number = models.IntegerField(blank=False)

    def get_number(self):
        return ???

    def save(self):
        ??? .save()

推荐答案

根据到目前为止的研究,我需要扩展保存功能并检查数据库中的先前值.

From what I have researched so far I would need to extend the save function and check the previous value in the db.

通常,对任何RDBMS来说,执行SELECT后再基于该SELECT进行插入或更新都是一个坏主意.因为这可能导致争用条件,所以数据库内置了避免这种争用条件的机制,通常速度更快.

Generally doing a SELECT followed by an insert or update based on that SELECT is a bad idea for any RDBMS. Because this can lead to race conditions and databases have built in mechanisms that avoid this race condition and are usually faster.

Postgresql具有序列类型.从现在开始,它将被包含在Django的下一个主要版本中的django.contrib.posgres中.创建一个这样的自定义迁移:

Postgresql has a Serial type. It will be included in the django.contrib.posgres from the next major release of Django but for now. Create a custom migration like this:

CREATE SEQUENCE my_serial START 1000;
ALTER TABLE myapp_mymodel ALTER COLUMN order_number SET DEFAULT nextval('my_serial');

如果您以前从未创建过自定义迁移,请查找

If you have never created a custom migration before, look up RunPython

这篇关于自动递增非pk字段(从1000开始)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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