本文介绍了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模型视图中的唯一发票编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 20:44