Django 2 How to use forign keys of one model in another model

41 Views Asked by At

I am new to django and I am building a cricket club management website in django. There are teams, players, grounds and match apps. In team apps.

Players Model:

class Players(models.Model):
    player_full_name = models.CharField(max_length=40)
    player_email = models.EmailField(unique=True)
    player_team = models.ManyToManyField(Teams)

Teams Model:

class Teams(models.Model):
    team_name = models.CharField(max_length=100)
    team_home_ground = models.ForeignKey(Grounds, on_delete=None, null=True, blank=True)

Match Model:

class AddMatch(models.Model):
    match_team_1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name='match_team1')
    match_team_2 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name='match_team2')
    match_ground = models.ForeignKey(Grounds, on_delete=None)
    match_date = models.DateField(default=timezone.now)

Now I want to add another model AddMatchRecod to submit match record and I will make form based on that model. In AddMatchRecod I want to have a field winning_team field, a drop down list of two fields from AddMatch model match_team_1 and match_team_2 as choices. Teams table has many teams I only want to present two teams that are participating in the match. How would I get that.

class MatchAddData(models.Model):
    team1 = ??
    team2 = ??

Second question. There is a model PlayersRecords which stores players data. There are 100s of players how would I get the 11 or 12 players that are part of team1 and team2 and display separately PlayerRecord model fields in form for each player.

Player Record Model:

class PlayersRecords(models.Model):
    player_full_name = models.ForeignKey(Players, on_delete=models.CASCADE)
    player_total_runs = models.IntegerField(default=0, blank=True)
    player_total_matches = models.IntegerField(default=0, blank=True)
    player_total_fours = models.IntegerField(default=0,blank=True)
    player_total_sixes = models.IntegerField(default=0,blank=True)
    player_total_centuries = models.IntegerField(default=0,blank=True)
    player_total_fifties = models.IntegerField(default=0,blank=True)

Thanks.

0

There are 0 best solutions below