Django模型视图中的唯一发票编号

编程入门 行业动态 更新时间:2024-10-28 06:30:29
本文介绍了Django模型视图中的唯一发票编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的发票有django模型.

I have a django model for my invoices.

现在,我需要每天(在我的Django Views函数中)生成唯一的发票编号.

Now I need to generate unique invoice numbers for each day (in my Django Views function).

例如,2016年4月7日的发票编号应为:16040701、16040702、16040703等.

Example, invoice no, for 7th April, 2016 shall be like: 16040701, 16040702, 16040703, etc.

如何实现?

推荐答案

我可以通过在Invoice模型中覆盖save()来做到这一点.首先,在模型中添加发票编号字段:

I would do this by overriding save() in your Invoice model. First, add a field for your invoice number to your model:

invoice_id = models.CharField(blank = True,max_length = 8)

然后,覆盖save()方法:

Then, override the save() method:

def save(self, *args, **kwargs): today = datetime.date.today() today_string = today.strftime('%y%m%d') next_invoice_number = '01' last_invoice = Invoice.objects.filter(invoice_id__startswith=today_string).order_by('invoice_id').last() if last_invoice: last_invoice_number = int(last_invoice.invoice_id[6:]) next_invoice_number = '{0:02d}'.format(last_invoice_number + 1) self.invoice_id = today_string + next_invoice_number super(Invoice, self).save(*args, **kwargs)

这将为您提供所需的格式 yymmdd ## .注意:如果您每天有99张以上的发票,则此功能将无效.如果需要的数目超过99,请将 {0:02d} 更改为 {0:03d} ,然后在invoice_id字段上设置 max_length = 9 .每天可容纳999张发票,格式为 yymmdd ### .

This will give you the format yymmdd## that you are looking for. Note: this will not work if you have more than 99 invoices per day. If you needed more than 99, change {0:02d} to {0:03d} and set max_length=9 on your invoice_id field. This will accommodate 999 invoices per day with the format yymmdd###.

更多推荐

Django模型视图中的唯一发票编号

本文发布于:2023-10-30 12:33:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   发票   模型   编号   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!