Django无法创建对象 - RelatedObjectDoesNotExist

时间:2017-01-09 14:30:46

标签: python django django-models

我有一个模型Payment和模型Invoice。模型发票的属性paymentOneToOneField字段null=Trueblank=True

问题是Django不允许我创建付款。

>>> Payment.objects.create(total_price=10)

RelatedObjectDoesNotExist: Payment has no invoice.

>>> Payment.objects.create(total_price=10,invoice=Invoice.objects.first())

TypeError: 'invoice' is an invalid keyword argument for this function

无法弄清楚为什么会这样。我希望Invoice有一个可选参数payment,反之亦然,因为Payment对象是在收到付款后创建的。

class Invoice(models.Model):
    identificator = models.UUIDField(default=uuid.uuid4, editable=False)
    order = models.OneToOneField('Job', related_name='invoice', on_delete=models.CASCADE)
    price_per_word = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=12)
    translator_revenue_in_percent = models.FloatField(null=True, blank=True)
    discount_in_percent = models.FloatField(default=0)
    final_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    estimated_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    paid = models.BooleanField(default=False)
    payment = models.OneToOneField('Payment', related_name='invoice', null=True, blank=True)
    __original_paid = None

    def save(self, *args, **kwargs):

        if not self.__original_paid and self.paid:
            self.__original_paid = True
            if self.order.translator:
                EventHandler.order_has_been_paid(self.order)

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

class Payment(models.Model):
    payment_identifier = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

    def save(self,*args,**kwargs):
        EventHandler.order_has_been_paid(self.invoice.order)
        super(Payment,self).save(*args,**kwargs)

你知道问题出在哪里吗?

1 个答案:

答案 0 :(得分:3)

您覆盖save模型的Payment方法,以访问显然不存在的self.invoice,因为尚未保存付款,请少说明发票。< / p>