Home > other >  Django - How to get self.id instance when creating new object
Django - How to get self.id instance when creating new object

Time:02-15

I am working with two classes, when i save the first one it will automatic create the other one, the field called "transaction" should be filled by self.id.

But i get this error message:

NOT NULL constraint failed: portfolios_portfoliotoken.transaction_id

this is the code that i am using:

PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl last.total_today_brl, order_value=self.total_cost_brl)

More details is possible to see below:



class Transaction(models.Model):
    id = models.AutoField(primary_key=True)
    date =  models.DateField(("Date"), default=date.today)
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    total_cost_brl = models.FloatField(editable=False)
    ...

    def save(self, *args, **kwargs):
        self.share_cost_brl = round(self.share_cost_brl, 2)
        self.total_cost_brl = round(self.shares_amount * self.share_cost_brl, 2)

        ...

        PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl last.total_today_brl, order_value=self.total_cost_brl)


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

    
class PortfolioToken(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
    total_today_brl = models.FloatField()
    order_value = models.FloatField()
    date =  models.DateField(("Date"), default=date.today)
    ...

CodePudding user response:

You should first call super().save(*args, **kwargs) to save the transaction, and then you can use this to construct the PortfolioToken:

class Transaction(models.Model):
    # …

    def save(self, *args, **kwargs):
        # …
        super().save(*args, **kwargs)
        PortfolioToken.objects.create(
            transaction_id=self.id,
            portfolio=self.portfolio,
            date=self.date,
            total_today_brl=self.total_cost_brl last.total_today_brl,
            order_value=self.total_cost_brl
        )
  • Related