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

时间:2015-03-20 12:07:41

标签: python django

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

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得到了:

  

管理员无法通过VoucherTypeMaster实例访问

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

1 个答案:

答案 0 :(得分:3)

覆盖凭证模型上的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)