Reputation: 1609
I have a master model which creates alphanumeric automatically for different types of Vouchers for different companies. How do I update the master model. The models:
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)
If I uncomment self.type.save() Traceback got:
Manager isn't accessible via VoucherTypeMaster instances
How to update the VoucherTypeMaster model with the next value? Using django 1.6.5, linux
Upvotes: 3
Views: 6425
Reputation: 1609
Overriding the save method on Voucher model and passing the VoucherTypeMaster and not its instance solved the problem: Increment the last_number, if the self.id is None
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)
Upvotes: 8