如何使用预定义的字母缩写部分声明自动递增的字母数字id字段(Django python) [英] How to declare a auto-incrementing alphanumerical id field with predefined aplphabetic part (Django python)

查看:126
本文介绍了如何使用预定义的字母缩写部分声明自动递增的字母数字id字段(Django python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Django开发应用程序.

I am developing an app in Django.

我想在模型中插入一个自动递增的字母数字ID字段,默认情况下,该字段具有一个固定的字母部分和一个自动递增的数字部分. 但是我也希望将可用性从管理部分更改为另一个id字母数字和ID,其中字母数字和数字部分不同. 请注意:我不想覆盖django默认ID字段,我只想在模型中包含一个字段,该字段将自动递增的字母数字值作为默认值.

I want to insert in my model an auto-incrementing alphanumerical ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value an auto-incrementing alphanumerical value.

示例:

所需的字母常量部分:ITM

Desired alphabetical constant part: ITM

所需的数字自动递增部分:00000

Desired numerical auto-incrementing part: 00000

这样,当模型中的每个对象生成时,都将获得默认的渐进值,例如:ITM00001,ITM00002,ITM00003,...

So that every object of my model, when generated, get default progressive values like: ITM00001, ITM00002, ITM00003, ...

我想将我的管理部分中的字段值更改为例如:ABC0000001,DFG0051,RST034,...

I would like to change the field value from my admin section into, for example: ABC0000001, DFG0051, RST034, ...

最大字段长度:10(也可以更高)

Max field length: 10 (It can be also higher)

我意识到我必须使用AutoField并以某种方式将常量字符串与自动递增的数字变量连接在一起,但是我不知道该怎么做.

I realize that I have to use AutoField and to somehow join the constant string with the auto-incrementing numerical variable, but I don't know how to do it.

class my_model(models.Model):

    Field_1 = models.CharField(max_length=10, blank=True, null=True)
    static_ID = models.AutoField(???)

推荐答案

已解决:

由于我不需要特定的ID长度,也不需要两个连续ID之间的恒定增量,因此每次创建模型中的对象时,都可以使用time.time()获取唯一的时间编号.然后,我可以将那个时间数字转换为字符串,并用一个常量前缀将其连接起来.

Since I don't need a specific length for my id, nor a constant increment between two consecutive ids, I can use time.time() to get a unique time number every time the object in the model is created. Then I can turn that time number into a string and concatenate it with a constant prefix.

models.py 中:

import time

def return_timestamped_id():
    prefix = "ITCH"     
    timestamp = str(int(time.time()*10000000))
    default_value = prefix + timestamp
    return(default_value)


class my_model(models.Model):        
    Field_1 = models.CharField(max_length=256)
    static_ID = models.CharField(max_length=256, blank=False, null=False, default=return_timestamped_id)

这篇关于如何使用预定义的字母缩写部分声明自动递增的字母数字id字段(Django python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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