python - 在 django 后端为新发票自动增加发票号

标签 python django django-admin django-admin-filters django-admin-tools

我想自动增加发票号码,它是 3 位字符和 4 位数字。

class Invoice:
    invoice_no = models.CharField(max_length=500, null=True, blank=True, validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',message='Invoice must be Alphanumeric',code='invalid_invoice number'),])

我在后端注册了这个模型。但是现在当我在管理员中点击创建发票时,发票应该会自动填写。当我再次在管理员中点击创建新发票时,invoice_number 应该加一并且应该是自动字段。

例如发票编号 MAG0001、MAG0002、MAG0003 等,当我点击创建新发票时,这应该是管理员中的自动字段。

最佳答案

定义一个函数来生成发票编号。

def increment_invoice_number():
    last_invoice = Invoice.objects.all().order_by('id').last()
    if not last_invoice:
         return 'MAG0001'
    invoice_no = last_invoice.invoice_no
    invoice_int = int(invoice_no.split('MAG')[-1])
    new_invoice_int = invoice_int + 1
    new_invoice_no = 'MAG' + str(new_invoice_int)
    return new_invoice_no

现在在您的模型文件中使用此函数作为默认值。

invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)

这只是一个想法。修改函数以匹配您首选的发票编号格式。

关于python - 在 django 后端为新发票自动增加发票号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198883/

相关文章:

python - 无法获取执行结果(SQL-Tools)

python - 在管理页面中编辑 M2M 的两侧

python - 你如何在 django 管理索引中添加一个新条目?

python - 在单个数据库调用中评估多个查询集

python - Django 管理界面上的链接断开

python - Django 管理没有错误 - 隐藏高级查找部分

python - django 缓存 session

python - 将文本和数据图表与 facet 结合?

python - Matplotlib 日期代码 - 没有明显原因超出 Locator.MAXTICKS 错误

django - DRF : Do DRF serializers, SerializerMethodField 有执行顺序