0
我有一個模型Payment
和模型Invoice
。模型發票具有屬性payment
,該屬性是OneToOneField
字段,其中null=True
和blank=True
。Django無法創建對象 - RelatedObjectDoesNotExist
問題是,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)
你知道問題在哪裏嗎?