gpt4 book ai didi

python - 如何在 django 的另一个模型保存方法中更新模型实例?

转载 作者:行者123 更新时间:2023-12-05 01:02:41 26 4
gpt4 key购买 nike

我有一个主模型,可以为不同公司的不同类型的凭证自动创建字母数字。如何更新主模型。模型:

class VoucherTypeMaster(models.Model):
code = models.CharField(max_length=12,null=True,blank=True)
description = models.CharField(max_length=30,null=True,blank=True)
last_number = models.IntegerField(null=True,blank=True)
company = models.ForeignKey(Company,
related_name='voucher_master_company')
class Meta:
unique_together = ('code','company')

class Voucher(models.Model):
type = models.ForeignKey(VoucherTypeMaster)
date = models.DateField(default=datetime.datetime.now().date())
company = models.ForeignKey(Company,
related_name='voucher_company')
number = models.CharField(max_length=20,null=True,blank=True)
narration = models.CharField(max_length=30,null=True,blank=True)
amount = models.DecimalField(decimal_places=2,max_digits=9)

# class Meta:
# unique_together = ('company','number','date')

def __unicode__(self):
return '%s - %s' %(self.number,self.narration)

def save(self, *args, **kwargs):
try:
voucher_type = VoucherTypeMaster.objects.get(
company=self.company,
code=self.type.code
)
voucher_type.last_number += 1
voucher_type.save()
self.number = voucher_type.last_number
# self.type.save() # throws exception
except Exception,e:
print e

super(Voucher, self).save(*args, **kwargs)

如果我取消注释 self.type.save() Traceback got:

Manager isn't accessible via VoucherTypeMaster instances

如何用下一个值更新 VoucherTypeMaster 模型?使用django 1.6.5,linux

最佳答案

覆盖 Voucher 模型的 save 方法并传递 VoucherTypeMaster 而不是它的实例解决了问题:如果 self.id 为 None,则增加 last_number

def save(self, *args, **kwargs):
try:
voucher_type = VoucherTypeMaster.objects.get(
company=self.company,
code=self.type.code
)
if self.id is None:
voucher_type.last_number = voucher_type.last_number+1
self.type = voucher_type
voucher_type.save()
except Exception,e:
print e
super(Voucher, self).save(*args, **kwargs)

关于python - 如何在 django 的另一个模型保存方法中更新模型实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29166148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com