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

标签 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 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/

相关文章:

python - 使用引导来增加样本数量是否有意义?那么,怎样才能实现呢?

Django:唯一 ID 生成器

python - 如何将图像保存到磁盘

Python/Pandas 从 Excel 表复制和粘贴

python - 如何让我的 SWIG 扩展模块与 Pickle 一起工作?

python - 如何添加到导航pinax(0.9a2)的链接?

python - 我正在尝试获取图像的 Base64 字符串

python - 查看使用 Heroku 和 S3 处理图像花费太多时间

python - 使用 Pandas 从 xml url 读取单个节点

python - 使用多列进行 Pandas 滚动应用