Wednesday, April 17, 2019

Re: compute model field by related field

1. Add a "winner" field to your Match
2. Implement a post_save  signal for the Match model that updates the "won" or "lost" fields for each Club in the match (simple if/then logic based on winner).

PS I think the default values for "won" and "lost" for a Club should be "0" and not "1".

On Tuesday, 16 April 2019 20:19:34 UTC+2, omar ahmed wrote:
hello ... i have two models "Club" class and "Match" class and it has foreign key to Club
now i want to increment "won" field (or draw or lost) in "Club" class by "score_local" and "score_visitor" in "Match" class ..
how can i do this
class Club(models.Model):
name = models.CharField(max_length=100)
won = models.IntegerField(default=1)
draw = models.IntegerField(default=1)
lost = models.IntegerField()
goal_for = models.IntegerField()
goal_against = models.IntegerField()


class Match(models.Model):
play_date = models.DateTimeField('play date')
club_visitor = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='match_club_visitor')
club_local = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='match_club_local')
score_visitor = models.IntegerField()
score_local = models.IntegerField()

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d3e8e12a-4b6f-435d-a681-a4a6727bbda0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment