我有一个有ID的发票应用。我想按年翻滚。也就是说,它每年都会从001开始。我的返回字符串是2014-001, 2014-002, 2015-001
...
但是,Django似乎不支持复合键。有没有办法做到这一点?
class Invoice(models.Model):
description = models.CharField(max_length=200)
date = models.DateField('Date Issued')
client = models.ForeignKey('organizations.Contact')
UNPAID = 'Unpaid'
PAID = 'Paid'
STATUS_CHOICES = (
(UNPAID, 'Unpaid'),
(PAID, 'Paid'),
)
status = models.CharField(max_length=6,
choices=STATUS_CHOICES, default=UNPAID)
notes = models.TextField(blank=True)
def __str__(self):
return (self.date.__str__().replace("-", "") +
"-" + self.id.__str__().zfill(3))
编辑新代码:
def save(self, *args, **kwargs):
if self.invoice_id is "":
current_date = self.date.year
previous_invoice = Invoice.objects.filter(invoice_id__contains=current_date).order_by('-id').first()
if previous_invoice is not None:
num = int(previous_invoice.invoice_id[5:])
else:
num = 1
self.invoice_id = '{year}-{num:03d}'.format(year=current_date, num=num)
super(Invoice, self).save(*args, **kwargs)
答案 0 :(得分:1)
您可以使用CharField作为ID,将其设置为主键并在保存时自动生成。
类似于以下内容应该有效:
class Invoice(models.Model):
id = models.CharField(max_length=8, null=False, primary_key=True)
...
def save(self, *args, **kwargs):
if self.pk is None:
current_year = datetime.now().year
previous_invoice = Invoice.objects.filter(id__contains=str(year)).order_by('-id').first()
if previous_invoice is not None:
num = int(previous_invoice.id[5:])
else:
num = 1
self.pk = '{year}-{num:03d}'.format(year=current_year, num=num)
super(Invoice, self).save(*args, **kwargs)
编辑:在primary_key
字段定义中添加缺少的id
属性。