0

I'm new in Django, got a problem. I have a method in Commodity Model:

@transaction.atomic
def payment(self):
    if self.owner.balance > self.price and self.active is False:
        self.act_time_till = now() + timedelta(days=1)
        self.owner.balance -= self.price
        # here i need to create a new Invoice object
        self.save()
        return True
    else:
        return False

And I have a different model - Invoice:

class Invoice(models.Model):
    commodity = models.ForeignKey(Commodity, on_delete=models.PROTECT)
    paid_till = models.DateTimeField(blank=False, null=False)
    value = models.DecimalField(max_digits=3, decimal_places=2, blank=False, null=False)

How can I create an instance of Invoice every time I make payment? Thanks!

1
  • you can just create an instance by calling Invoice.objects.create(**data), also you could use this anywhere you needed Commented Jun 19, 2018 at 10:40

2 Answers 2

1

You can just call inside this method.

@transaction.atomic
def payment(self):
   if self.owner.balance > self.price and self.active is False:
     self.act_time_till = now() + timedelta(days=1)
     self.owner.balance -= self.price
     # here i need to create a new Invoice object
     self.save()
     ## After this line you can create invoice object instance
     Invoice.objects.create(commodity=self, paid_till=self.act_paid_till, value=self.price)  
    return True
   else:
     return False
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It was PyCharm marked this as error. I had a trouble with field type, but i thought I was doing wrong.
1
# considering that you have invoice object available in the module. If not then you
# need to import it first.
Invoice.objects.create(commodity=self, paid_till=self.act_paid_till, value=self.price)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.