简体   繁体   English

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

[英]How to update a model instance in another model save method in django?

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: 如果我取消注释self.type.save(),则Traceback得到:

Manager isn't accessible via VoucherTypeMaster instances 无法通过VoucherTypeMaster实例访问Manager

How to update the VoucherTypeMaster model with the next value? 如何使用下一个值更新VoucherTypeMaster模型? Using django 1.6.5, linux 使用Django 1.6.5,Linux

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 覆盖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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM