Groups are nothing but models
.
class Player(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
Above, the Player
model
is for adding players. Now, if you want to group those players into teams, you'd do something like below:
class Team(models.Model):
players = models.ManyToManyField(Player)
team_name = models.CharField(max_length=100)
Now, you just have to create a team and keep adding players to it. Pretty easy, right?
Okay fine until now. Let's say, there were 4 matches today which means 8 teams played those matches. Out of the total players who played today, 15 got injured, and 10 got banned from playing the next match. So if you want to make groups for injured and banned players, you would do something like below:
class Injured(models.Model):
players = models.ManyToManyField(Player)
class Banned(models.Model):
players = models.ManyToManyField(Player)
That's it.
Now, the question is why would you use groups?
Of course, there's no need of writing group models, you have other options too.
class Player(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
team = models.CharField(max_length=100)
is_injured = models.BooleanField(default=False)
is_banned = models.BooleanField(default=False)
Now think: 15 players were injured, which means you would have to update 15 players' is_injured
to True
. 8 were banned, which means you'd have to change 8 players' is_banned
to True
. Plus, you'd have to keep writing the name of every player's team again and again. It is really very time consuming. Now do you see the importance of groups?
Where does this code live?
In your models.py
file.