I am trying to put together a Django app that will show the teams and games for my fantasy football league. I have taken a few cracks at the models, but I can't get my head wrapped around how they will relate.
This is what I am trying to accomplish:
Each year, there are six teams that make the "Toilet Bowl" tournament, which will crown the worst team in the league.
There are three rounds.
The worst two teams are not playing the first round. That leaves team 1 playing team 4 and team 2 playing team 3.
In round 2, teams 1 and 2 play the losers from round 1.
In round 3, the remaining two teams play for the title.
These are the models that I have so far. I know that they're not optimal.
class Owner(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=100)
phone = models.CharField(max_length=12, null=True)
def __str__(self):
return "%s" % (self.name)
class Team(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Game(models.Model):
year = models.SmallIntegerField(
validators=[MinValueValidator(2010),
MaxValueValidator(2999),
RegexValidator("^(20)([1-5][0-9])$")
])
round = models.SmallIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(3)])
teams = models.ManyToManyField(Team)
#teams = models.ForeignKey(Team, on_delete=models.CASCADE)
#team1_score = models.IntegerField(default=0)
#team2_id = models.ForeignKey(Team, on_delete=models.CASCADE)
#team2_score = models.IntegerField(default=0)
def __repr__(self):
return f"{self.round}, {self.year}, {self.teams}"
I would like to have fields for team scores in the Game model, but with the ManyToManyField type, I am not sure how to reference a team to a score. I am also not crazy about having the round number and year in the Game model, either, but I'm not sure how I'd break them out into their own models and relate them back to Game. I'm also not sure it's standard practice to have a model with only one field (say, Year).
Thanks in advance. This is my first Django app and I've been able to figure most of it out based on searches, but this schema has me stumped.
I'm happy to provide any other information that is needed.
In this case, instead of using a many to many field, you should create a third table that will have as fields the foreign key of the game, the foreign key of the team and the score, remember to define in the Meta the field unique_together so that the keys foreigners are unique together
class GameTeam(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
score = models.PositiveSmallIntegerField()
class Meta:
unique_together = [['game', 'team']]
Related
Im creating 2-step form. In first part captain is choosing one of his teams, in second i'm retrieving chosen team from first step and creating queryset based on it. Second form should only filter teams that doesn't have players in common with team from first step. Each team has only 3 players.
class Team(models.Model):
name = models.CharField(max_length=200, null=True, unique=True)
captain = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="captain")
team_creation_date = models.DateTimeField(auto_now_add=True, null=True)
players = models.ManyToManyField(Player, through="PlayerTeam", related_name="players")
class PlayerTeam(models.Model):
player = models.ForeignKey(Player,on_delete=models.CASCADE)
team = models.ForeignKey(Team,on_delete=models.CASCADE)
join_date = models.DateField(auto_now_add=True)
One solution without using Q is just to exclude the teams that that have common players.
selected_team = Team.objects.get(...) # get selected team
not_allowed_players = selected.team.players.all()
teams = Team.objects.all().exclude(players__in=not_allowed_players)
Such a question, I want to create a price comparison site, there are two ideas how to implement a list of prices from different stores.
First via ForeignKey
class Price(models.Model):
price = models.DecimalField()
shop = models.CharField()
class Product(models.Model):
name = models.CharField(max_length=255)
prices = models.ForeignKey()
JSONfield second method
class Product(models.Model):
name = models.CharField(max_length=255)
data = JSONField()
""" Product.objects.create(name='product', data={'price': 999,
'shop': 'Amazon.com'}
def __str__(self):
return self.name
If anyone has experience, what works faster and more reliable if a large number of goods? Thanks for the early ones.
I am building a school timetable app for each room? There are my models. Is there anything i am missing?
class Building(models.Model):
bid = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=255, unique=True)
class Meta:
ordering = ['bid']
def __str__(self):
return f'{self.bid}'
class Room(models.Model):
building = models.ForeignKey(Building, on_delete=models.CASCADE,
related_name='rooms')
number = models.PositiveIntegerField()
availability = models.BooleanField(default=False)
power = models.BooleanField(default=False)
class Meta:
ordering = ['building', 'number']
unique_together = ['building', 'number']
def __str__(self):
return f'{self.building.bid}/{self.number}'
class Occurrence(models.Model):
date = models.DateField('Date')
start_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='start_at')
end_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='end_at')
class Meta:
abstract = True
class Period(models.Model):
start = models.TimeField()
end = models.TimeField()
objects = PeriodManager()
class Meta:
ordering = ['start']
def __str__(self):
return f'{self.start}-{self.end}'
def check_time(self):
return True if self.start < self.end else False
def check_overlap(self):
pass
class TimetableModel(models.Model):
class Meta:
abstract =True
There will be a model name Booking which extends from Occurrence to allow students register to use a room in periods. I would like to make a Timetable model link to a Room Model for providing to context for rendering different weeks timetable for a room and Period models which are resemble school periods. Any advises?
I think you may need to re-think your actual models and what you're trying to achieve.
Having a look at your models you seemed to create models for different aspects of what you're trying to do but there doesn't seems to be coherence between the models.
For instance one way to look at it would be as follows:
Building
- Name
Room
- Number
- Building (FK)
Booking
- Room
- Period (you could just have statically defined list assume these are fixed)
- Duration (number of periods, this removes the need to specify end as you can calculate it.
To make a booking you need to know the following:
- The room you want to book
- The period you want to use it
- How long you'd like to book it for (ie. 2 periods)
From a data perspective that's probably the simplest models you can build (simple is always better). In terms of showing what is available you can do that at the point where you're making a booking (booking form).
I hope that gives you some idea of how to approach this, I didn't create models in this answer as I think your question wasn't really a technical how to but more of a point in the right direction.
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.
I'm still learning about how to setup up relational databases. I'm trying to create a db that tracks universities, departments, and their programs. My question is a relationship one. Each university might have one or more departments. This relationship should then be a many to many. Each department may have one or more programs, so I can see the relationship between the department and the programs being many to many.
The problem that I have is if I want to have a department that belongs to a university, I feel like I should use an intermediary to attach a program to that department. But then, if I want to add another program to the same department, I would end up having two of the same departments belonging to the one university. This doesn't seem right.
In other words:
class Department(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class Universities(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
departments = models.ManyToManyField(Department,through='UniversityHasDepartment')
class Program(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class UniversityHasDepartment(models.Model):
university = models.ForeignKey(Universities)
department = models.ForeignKey(Department)
program = models.ForeignKey(Program)
I think you want to use foreign keys. (one to many relationships).
Each university can have multiple departments but a department can only have 1 university.
Each department can have multiple programs but a program can only have 1 department.
class University(models.Model):
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Department(models.Model):
university = models.ForeignKey(University, related_name='departments')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Program(models.Model):
department = models.ForeignKey(Department, related_name='programs')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)