Shailendra Singh
Shailendra Singh

Reputation: 13

How to Update field of Django model based on another model with foreign key relation

I have two models Betslip and Bet,I want to update value of Betslip.settled_status to 'Lost', if Bet.settlement_status is 'half_lost' or 'lost', can anyone create a method for it ?

class Betslip(models.Model):
    SETTLED_STATUS_CHOICE = (
        ('InGame','InGame'),
        ('Won','Won'),
        ('Lost','Lost'),
        ('Refunded','Refunded')
    )
    settled_status = models.CharField(choices=SETTLED_STATUS_CHOICE,max_length=30)


class Bet(models.Model):
    SETTLEMENT_STATUS_CHOICE = (
        ('','select'),
        ('won','won'),
        ('lost','lost'),
        ('refund','Refund'),
        ('half_won','half_won'),
        ('half_lost','half_lost'),
    )

  
    settlement_status = models.CharField(choices=SETTLEMENT_STATUS_CHOICE,max_length=30,)
    betslip = models.ForeignKey(Betslip,on_delete=models.CASCADE,related_name='bet')```

Upvotes: 1

Views: 1391

Answers (2)

anonymous
anonymous

Reputation: 36

you can understand about @property from this discussion and for using the bets object for getting bets' settlement status property you may use "reverse related object lookup" aka _set inside the Betlip property(since you have used foreign key for Betslip in Bet)

Upvotes: 2

AlexZ
AlexZ

Reputation: 143

you can do something like this:

In Bet model try this:

def update_settled_status(self):
    if self.settlement_status in ['lost','half_won']:
        self.betslip.settled_status = 'Lost'
        self.betslip.save()

Upvotes: 0

Related Questions